我有以下 Rust 代码。
trait X<'a> {
fn x(&self) -> &'a [f64];
}
struct Owned{
x: Vec<f64>,
}
struct Ref<'a> {
x: &'a[f64],
}
我想为
X
和 Ref
实现 Owned
。
对于Ref
来说,这很简单。
impl<'a> X<'a> for Ref<'a> {
fn x(&self) -> &'a [f64] { self.x }
}
对于
Owned
,我希望fn x(&self)
返回&self.x
,但我不知道如何说Owned
实现了X<'lifetime-of-the-struct-itself>
。 我怎样才能做到这一点?
不要向特征添加生命周期参数,而是添加用于方法返回类型的通用关联类型:
trait X {
type Out<'out> where Self: 'out;
fn x(&self) -> Self::Out<'_>;
}
struct Owned {
x: Vec<f64>,
}
struct Ref<'a> {
x: &'a [f64],
}
impl<'a> X for Ref<'a> {
type Out<'out> = &'a [f64] where 'a: 'out;
fn x(&self) -> &'a [f64] { self.x }
}
impl X for Owned {
type Out<'out> = &'out [f64];
fn x(&self) -> &[f64] { &self.x }
}