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有一个方法来生成一个引用为A的B实例,并且B可能有许多方法访问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>发布于 2018-05-09 18:01:16
特征对象的默认生存期是'static。您需要为nb()函数返回的特征对象添加一个显式的生命周期绑定:
impl A {
fn nb<'s>(&'s self) -> Box<BT+'s> {
Box::new(B{a: self})
}
}https://stackoverflow.com/questions/50248219
复制相似问题