Rust 如何将借来的价值保存到struct';它生锈了

Rust 如何将借来的价值保存到struct';它生锈了,rust,ownership,tokio,Rust,Ownership,Tokio,我只想在结构中使用tokio::net::TcpStream.split方法,并将其作为字段变量,但我得到了错误error[E0597]:“stream”的寿命不够长。当我试图将一个借来的值保存到struct的字段(如struct std::path::path)时,我多次遇到这种问题。我知道使用PathBuf可以解决Path问题,但这次我不确定。你能给我一个建议让它工作吗 使用tokio::net::TcpStream; 使用tokio::net::tcp:{ReadHalf,WriteHal

我只想在结构中使用
tokio::net::TcpStream.split
方法,并将其作为字段变量,但我得到了错误
error[E0597]:“stream”的寿命不够长。当我试图将一个借来的值保存到struct的字段(如
struct std::path::path
)时,我多次遇到这种问题。我知道使用
PathBuf
可以解决
Path
问题,但这次我不确定。你能给我一个建议让它工作吗

使用tokio::net::TcpStream;
使用tokio::net::tcp:{ReadHalf,WriteHalf};
结构TT>,

pub-writer:Option TT问题在于流的读写部分都借用了对创建它们的流的引用。在代码中,原始流被丢弃在函数末尾,这将使这些引用无效。最简单的解决方案是将
set\u reader\u和\u writer
的签名更改为获取
&mut流,而不是获取所有权


这是一个可以理解的错误,因为
split
的签名没有明确表示其生命周期(即
stream
必须至少与返回值一样长)。但是,如果您检查,它会显示
ReadHalf
WriteHalf
的生存期(以及为什么允许从函数签名中删除它们)。

您需要通过引用获取TcpStream,以便您可以将TT的生存期定义为短于TcpStream的生存期。在这里,您将TcpStream移动到方法中,然后拆分它(借用它),然后。。。它死了,所以借款无效。或者,将
Rc
存储在两个字段或类似字段中。
$ 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`.