rust 寿命错误:一生可能活得不够长

guz6ccqo  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(104)

我有一个错误,我不明白当我编译我的 rust 代码。

error: lifetime may not live long enough
  --> src\tls_rustls.rs:88:9
   |
51 | impl<'a> Tls<Certificate> for EstClientRustls<'a> {
   |      -- lifetime `'a` defined here
52 |     fn open(&mut self, host: &str, port: i32, chain: &Vec<Certificate>) {
   |             - let's call the lifetime of this reference `'1`
...
88 |         self.tls = Some(tls);
   |         ^^^^^^^^^^^^^^^^^^^^ assignment requires that `'1` must outlive `'a`

产生错误的程式码为:

pub trait Tls<T> {
    fn open(&mut self, host: &str, port: i32, chain: &Vec<T>);
    fn close(&self);
}

pub struct EstClientRustls<'a> {
    client: Option<ClientConnection>,
    sock: Option<TcpStream>,
    tls: Option<Stream<'a, ClientConnection, TcpStream>>
}

impl<'a> Tls<Certificate> for EstClientRustls<'a> {

    fn open(&mut self, host: &str, port: i32, chain: &Vec<Certificate>) {
      let client = ClientConnection::new(rc_config, tls_server_name).unwrap();
      let sock = TcpStream::connect(host_port).unwrap();

      self.client = Some(client);
      self.sock = Some(sock);

      let tls = Stream::new(
        self.client.as_mut().unwrap(),
        self.sock.as_mut().unwrap());

      self.tls = Some(tls);
    }
}

任何人都可以帮助我?技术说明:rustc 1.64.0(a55 dd 71 d5 2022年9月19日)库:

  • 铁 rust 色-〉“0.20.7”
  • “1.0.1”中的字符串
  • x509-解析器-〉“0.14.0”
ccrfmcuu

ccrfmcuu1#

感谢Ali Mirghasemi提供的解决方案
将特征定义更改为

pub trait Tls<'a, T> {
    fn open(&'a mut self, host: &str, port: i32, chain: &Vec<T>);
    fn close(&self);
}

并且实现本身

fn open(&'a mut self, host: &str, port: i32, chain: &Vec<Certificate>) {

解决问题

相关问题