gpt4 book ai didi

Rust 提示生命周期要求冲突,没有迭代器或闭包

转载 作者:行者123 更新时间:2023-11-29 08:25:12 25 4
gpt4 key购买 nike

我正在尝试自学 Rust。我熟悉 C++ 和 Scala,但 Rust 对我来说仍然是一种 Perlish 语言。

为了这段代码,我已经和借用检查员争论了两天。这对我来说似乎很清楚,但我无法让 Rust 同意。

这很简单,我可以得到代码但仍然会产生错误:

use std::io;

fn main() {
let mut streams: StdStreams = StdStreams {
stderr: &mut io::stderr(),
};
let command = Command {};
let streams_ref: &mut StdStreams = &mut streams;
command.go(streams_ref);
}

pub struct StdStreams<'a> {
stderr: &'a mut io::Write,
}

pub struct Command {}

impl Command {
pub fn go(&self, streams: &mut ::StdStreams) {
let mut server = Server { streams };
}
}

pub struct Server<'a> {
pub streams: &'a mut StdStreams<'a>,
}

这是编译器的意见:

error[E0495]: cannot infer an appropriate lifetime for lifetime parameter `'a` due to conflicting requirements
--> src/main.rs:20:26
|
20 | let mut server = Server { streams };
| ^^^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #2 defined on the method body at 19:5...
--> src/main.rs:19:5
|
19 | / pub fn go(&self, streams: &mut ::StdStreams) {
20 | | let mut server = Server { streams };
21 | | }
| |_____^
note: ...so that reference does not outlive borrowed content
--> src/main.rs:20:35
|
20 | let mut server = Server { streams };
| ^^^^^^^
note: but, the lifetime must be valid for the anonymous lifetime #3 defined on the method body at 19:5...
--> src/main.rs:19:5
|
19 | / pub fn go(&self, streams: &mut ::StdStreams) {
20 | | let mut server = Server { streams };
21 | | }
| |_____^
note: ...so that expression is assignable (expected &mut StdStreams<'_>, found &mut StdStreams<'_>)
--> src/main.rs:20:35
|
20 | let mut server = Server { streams };
| ^^^^^^^

我似乎很清楚,我存储有问题的引用的项目将超出范围并立即消失,同时它存储的引用也会消失,所以不应该有任何不愉快。

我也发现这是不必要的讽刺:expected &mut StdStreams<'_>, found &mut StdStreams<'_> .

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com