简体   繁体   中英

casting struct to trait with lifetime got “cannot infer an appropriate lifetime for lifetime parameter `'a` due to conflicting requirements”

trait BT {
    fn get_a(&self) -> &A;
}

#[derive(Debug)]
struct A {
    v: i32,
}

impl A {
    fn nb(&self) -> Box<BT> {
        Box::new(B { a: self })
    }
}

#[derive(Debug)]
struct B<'a> {
    a: &'a A,
}

impl<'a> BT for B<'a> {
    fn get_a(&self) -> &A {
        return self.a;
    }
}

fn main() {
    println!("{:?}", A { v: 32 }.nb().get_a());
}

A has a method to generate a B instance with a reference of A , and B might have many methods access Ba (A's reference in B). If let A.nb() return B instead of BT , the code would work well.

I'm new to Rust. This problem has troubled me all day. What should I do to make this code work? Thanks!

The whole error report:

error[E0495]: cannot infer an appropriate lifetime for lifetime parameter `'a` due to conflicting requirements
  --> src\socket\msg\message.rs:53:26
   |
53 |                 Box::new(B{a: self})
   |                          ^
   |
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 52:13...
  --> src\socket\msg\message.rs:52:13
   |
52 | /             fn nb(&self) -> Box<BT> {
53 | |                 Box::new(B{a: self})
54 | |             }
   | |_____________^
note: ...so that reference does not outlive borrowed content
  --> src\socket\msg\message.rs:53:31
   |
53 |                 Box::new(B{a: self})
   |                               ^^^^
   = note: but, the lifetime must be valid for the static lifetime...
   = note: ...so that the expression is assignable:
           expected std::boxed::Box<socket::msg::message::test::test::BT + 'static>
              found std::boxed::Box<socket::msg::message::test::test::BT>

The default lifetime of a trait object is 'static . You need to add an explicit lifetime bound to the trait object returned by nb() function:

impl A {
    fn nb<'s>(&'s self) -> Box<BT+'s> {
        Box::new(B{a: self})
    }
}

Inference of Trait Object Lifetimes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM