[英]Error returning reference to a temporary value when implementing a trait for a type reference
I am trying to implement a simple trait which returns a reference to some data ( GetData
).我正在尝试实现一个简单的特征,它返回对某些数据( GetData
)的引用。 For different reasons, I need to implement this trait for reference to my type ( &Base<T>
).由于不同的原因,我需要实现这个特征以引用我的类型( &Base<T>
)。 I also would like to have a wrapper type that owns the base type and implements the trait.我还想要一个拥有基本类型并实现特征的包装器类型。
The simplified example looks like this:简化的示例如下所示:
// Trait
trait GetData<T> {
fn get_data(&self) -> &T;
}
// Base type
struct Base<T> {
pub data: T,
}
impl<T> GetData<T> for &Base<T> {
fn get_data(&self) -> &T {
&self.data
}
}
// Wrapper type owning a Base type
struct Wrapper<T> {
base: Base<T>,
//...
}
impl<T> GetData<T> for &Wrapper<T> {
fn get_data(&self) -> &T {
(&self.base).get_data() // E0515: returns a value referencing data owned by the current function
//&self.base.data // This works fine!
}
}
When implementing get_data
for a &Wrapper<T>
I get an error of returning a temporary value from my function.为&Wrapper<T>
实现get_data
时,我收到从 function 返回临时值的错误。 As I understand &self.base
is borrowed by GetData::get_data
.据我了解&self.base
是由GetData::get_data
借用的。 I am not sure how to resolve it though.我不知道如何解决它。 All my attempts to add explicit lifetimes didn't work so far.到目前为止,我所有添加显式生命周期的尝试都没有奏效。
The issue is with this:问题在于:
impl<T> GetData<T> for &Base<T> {
fn get_data(&self) -> &T {
&self.data
}
}
Now in all honesty I've no idea why you'd bother implementing only for &Base
instead of just implementing for Base
.现在老实说,我不知道你为什么要费心只为&Base
实现而不是只为Base
实现。 But that's the cause of the issue because the lifetime of the Base and the lifetime of the self are not the same and your self
is an &&Base<T>
.但这就是问题的原因,因为 Base 的生命周期和 self 的生命周期不同,而你的self
是&&Base<T>
。
This means in:这意味着:
fn get_data(&self) -> &T {
(&self.base).get_data() // E0515: returns a value referencing data owned by the current function
//&self.base.data // This works fine!
}
the lifetime of the result is that of &self.base
which is purely local to the function, instead of being the expected lifetime of self
.结果的生命周期是&self.base
的生命周期,它纯粹是 function 的本地生命周期,而不是self
的预期生命周期。
If you如果你
impl<T> GetData<T> for Base<T> {
fn get_data(&self) -> &T {
&self.data
}
}
then everything works out of the box.然后一切都开箱即用。
Can't help but think the entire thing smells of OO-thinking, a GetData
trait stinks of Java/C# interface.不禁想到整个事情都带有 OO 思维的味道, GetData
特征散发着 Java/C# 接口的味道。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.