[英]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). A
必须产生的方法B
与参考实例A
和B
可能有许多方法来访问Ba
(A在B参考)。 If let A.nb()
return B
instead of BT
, the code would work well. 如果让A.nb()
返回B
而不是BT
,则代码将运行良好。
I'm new to Rust. 我是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
. 特征对象的默认生存期为'static
。 You need to add an explicit lifetime bound to the trait object returned by nb()
function: 您需要添加绑定到nb()
函数返回的trait对象的显式生命周期:
impl A {
fn nb<'s>(&'s self) -> Box<BT+'s> {
Box::new(B{a: self})
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.