![](/img/trans.png)
[英]cannot infer an appropriate lifetime for lifetime parameter `'de` due to conflicting requirements for struct made of enums with Serde Deserialize
[英]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
必須產生的方法B
與參考實例A
和B
可能有許多方法來訪問Ba
(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>
特征對象的默認生存期為'static
。 您需要添加綁定到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.