[英]cannot infer an appropriate lifetime for borrow expression due to conflicting requirements
pub struct FooStruct<'a> {
pub bars: Vec<&'a str>,
}
pub trait FooTrait<'a> {
fn getBars(&self) -> &'a Vec<&'a str>;
}
impl<'a> FooTrait<'a> for FooStruct<'a> {
fn getBars(&self) -> &'a Vec<&'a str> {
&self.bars // cannot infer an appropriate lifetime for borrow expression due to conflicting requirements
}
}
我不明白需求沖突來自哪里。 Afaik 沒有沖突,因為只要FooStruct
存在,一切都會存在。
讓我們把它拆開:
pub struct FooStruct<'a> {
pub bars: Vec<&'a str>,
}
FooStruct
包含一個容器,其中包含生命周期'a
的字符串切片。 容器的生命周期對應於FooStruct
的生命周期。
pub trait FooTrait<'a> {
fn getBars(&self) -> &'a Vec<&'a str>;
}
FooTrait
希望getBars
返回對包含生命周期'a
字符串切片的容器的引用。 返回的引用的生命周期也應該是'a
。
impl<'a> FooTrait<'a> for FooStruct<'a> {
fn getBars(&self) -> &'a Vec<&'a str> {
&self.bars
}
}
在這里, getBars
返回對self.bars
的引用,它是一個包含生命周期'a
的字符串切片的容器。 到目前為止,一切都很好。
&self.bars
的生命周期是多少? 它對應於self
的生命周期(即各自的FooStruct
)。self
的壽命是多少? 它是'self
(隱含的生命周期)。 但是, FooTrait
要求返回的引用生命周期為'a
,因此與FooTrait
的聲明不匹配。
一種解決方案是在FooTrait
中分離生命周期:
pub trait FooTrait<'a> {
fn getBars<'s>(&'s self) -> &'s Vec<&'a str>;
}
impl<'a> FooTrait<'a> for FooStruct<'a> {
fn getBars<'s>(&'s self) -> &'s Vec<&'a str> {
&self.bars
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.