我只想在结构中使用tokio::net::TcpStream.split
方法并将其保留为字段变量,但是出现了error[E0597]: 'stream' does not live long enough
错误。当我尝试保留借来的值到Struct std::path::Path
之类的struct字段时,我会多次遇到此类问题。我知道Path
问题将通过使用PathBuf
解决,但我不确定这次。你能给我一个建议使其工作吗?
use tokio::net::TcpStream;
use tokio::net::tcp::{ReadHalf, WriteHalf};
struct TT<'a>{
pub reader: Option<ReadHalf<'a>>,
pub writer: Option<WriteHalf<'a>>,
}
impl<'a> TT<'a> {
fn set_reader_and_writer(&mut self, mut stream: TcpStream) {
let (reader, writer) = stream.split();
self.reader = Some(reader);
self.writer = Some(writer);
}
}
$ cargo build [master|…4]
Blocking waiting for file lock on build directory
Compiling tcpst v0.1.0 (/tmp/tcpst)
error[E0597]: `stream` does not live long enough
--> src/main.rs:11:32
|
9 | impl<'a> TT<'a> {
| -- lifetime `'a` defined here
10 | fn set_reader_and_writer(&mut self, mut stream: TcpStream) {
11 | let (reader, writer) = stream.split();
| ^^^^^^ borrowed value does not live long enough
12 | self.reader = Some(reader);
| -------------------------- assignment requires that `stream` is borrowed for `'a`
13 | self.writer = Some(writer);
14 | }
| - `stream` dropped here while still borrowed
error: aborting due to previous error
For more information about this error, try `rustc --explain E0597`.
error: could not compile `tcpst`.
最佳答案
问题是流的一半读写都借用了对它们创建的流的引用。在您的代码中,原始流将在函数末尾删除,这将使这些引用无效。最简单的解决方案是将set_reader_and_writer
的签名更改为采用&mut stream
而不是所有权。
这是一个很容易理解的错误,因为split
的签名没有明确表明其生存期(stream
的生存期至少应与返回值一样长)。但是,如果您检查the source,它将显示ReadHalf
和WriteHalf
的生存期(以及为什么允许从函数签名中删除它们)。
关于rust - 如何在Rust中将借来的值保存到struct字段中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61405786/