1

我只想tokio::net::TcpStream.split在结构中使用方法并将其保留为字段变量,但出现错误error[E0597]: 'stream' does not live long enough。当我试图将借来的值保存到 struct 的字段(如Struct std::path::Path. 我知道Path问题会通过 using 得到解决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`.
4

1 回答 1

1

问题是流的读取和写入部分都借用了对创建它们的流的引用。在您的代码中,原始流被丢弃在函数的末尾,这将使这些引用无效。最简单的解决方案是将签名更改set_reader_and_writer为采取 a&mut stream而不是取得所有权。

这是一个非常容易理解的错误,因为 for 的签名split没有明确其生命周期(它stream必须至少与返回值一样长)。但是,如果您检查source,它会显示ReadHalfandWriteHalf生命周期(以及为什么允许它们从函数签名中省略)。

于 2020-04-24T14:00:35.450 回答