由于需求冲突,将结构转换为具有生命周期的特征“无法推断生命周期参数''a'的适当生命周期”

时间:2018-05-09 07:52:08

标签: rust

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有一种生成B实例的方法,其引用为AB可能有多种方法访问B.a(A的引用) B)。如果让A.nb()返回B而不是BT,代码就可以正常运行。

我是Rust的新手。这个问题一整天困扰着我。我该怎么做才能使这段代码有效?谢谢!

整个错误报告:

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>

1 个答案:

答案 0 :(得分:3)

特质对象的默认生命周期为'static。您需要为nb()函数返回的特征对象添加显式生命周期绑定:

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

Inference of Trait Object Lifetimes