【问题标题】:Trait method that can be implemented to either return a reference or an owned value可以实现返回引用或拥有值的特征方法
【发布时间】:2017-09-05 12:03:03
【问题描述】:

我正在尝试使用可以实现返回引用或拥有值的方法来定义特征。

类似:

struct Type;
trait Trait {
    type Value;
    fn f(&self) -> Self::Value;
}
impl Trait for () {
    type Value = Type;
    fn f(&self) -> Self::Value {
        Type
    }
}
impl Trait for (Type,) {
    type Value = &Type; // error[E0106]: missing lifetime specifier
    fn f(&self) -> Self::Value {
        &self.0
    }
}

这段代码不起作用,因为&Type 缺少生命周期说明符。我希望&Type 与&self 具有相同的生命周期(即fn f<'a>(&'a self) -> &'a Type),但我不知道如何在Rust 中表达这一点。

我设法找到了几种方法来使这段代码工作,但我不喜欢其中任何一种:

  1. 为特征本身添加显式生命周期:

    trait Trait<'a> {
        type Value;
        fn f<'b>(&'b self) -> Self::Value where 'b: 'a;
    }
    impl<'a> Trait<'a> for () {
        type Value = Type;
        fn f<'b>(&'b self) -> Self::Value
            where 'b: 'a
        {
            Type
        }
    }
    impl<'a> Trait<'a> for (Type,) {
        type Value = &'a Type;
        fn f<'b>(&'b self) -> Self::Value
            where 'b: 'a
        {
            &self.0
        }
    }
    

    我不喜欢这个解决方案的是,任何使用 Trait 的东西都需要一个明确的生命周期(我认为这并不是本质上必需的),而且这个 trait 的实现似乎不必要地复杂。

  2. 返回可能是也可能不是参考的东西——比如std::borrow::Cow:

    trait Trait {
        type Value;
        fn f<'a>(&'a self) -> Cow<'a, Self::Value>;
    }
    impl Trait for () {
        type Value = Type;
        fn f<'a>(&'a self) -> Cow<'a, Self::Value> {
            Cow::Owned(Type)
        }
    }
    impl Trait for (Type,) {
        type Value = Type;
        fn f<'a>(&'a self) -> Cow<'a, Self::Value> {
            Cow::Borrowed(&self.0)
        }
    }
    

    我不喜欢这个解决方案是().f() 是Cow&lt;_&gt;:我需要调用().f().into_owned() 来获取我的Type。这似乎没有必要(当使用Trait 作为特征对象时,可能会导致一些可忽略的运行时开销)。

    还要注意Cow 不好,因为它要求Self::Value 实现ToOwned(因此实际上是Clone),这要求太强了。无论如何,在没有这些限制的情况下实现Cow 的替代方案很容易。

这个问题还有其他解决方案吗?什么是标准的/最常见的/首选的?

【问题讨论】:

  • “为特征本身添加显式生命周期”正是我的做法(尽管可能只有一个生命周期)。也许你可以进一步解释为什么你“相信不是本质上必要的”,因为对我来说这似乎是非常必要的——你需要将生命周期绑定到Self 类型以防止使用引用在值超出范围之后。
  • @Shepmaster:哦,你是说trait Trait&lt;'a&gt; { type Value; fn f( &amp;'a self ) -&gt; Self::Value; }?我确信我尝试过它并没有奏效,但显然我错了。无论如何,您是对的,阅读您的评论并在没有 'b 的情况下定义特征让我意识到 'a 需要成为特征的内在...
  • 是的,我会使用impl Trait&lt;'static&gt; for () { ... },但除此之外......
  • @Shepmaster 为什么?功能上有什么区别,还是显示意图的问题?谢谢你,你在这里真的很有帮助。
  • 嗯,想多了,'static 可能行不通;它可能使 calling 该方法实际上是不可能的。必须玩它才能弄清楚。

标签: reference rust traits lifetime


【解决方案1】:

这可以通过使用额外的关联对象来选择是否返回类型或引用以及一些元编程魔法来解决。

首先,一些辅助类型:

struct Value;
struct Reference;

trait ReturnKind<'a, T: ?Sized + 'a> {
    type Type: ?Sized;
}
impl<'a, T: ?Sized + 'a> ReturnKind<'a, T> for Value {
    type Type = T;
}
impl<'a, T: ?Sized + 'a> ReturnKind<'a, T> for Reference {
    type Type = &'a T;
}

ReturnKind 是一个“类型级函数”,当“输入”为Value 时返回T,&amp;T 为Reference。

然后是特质:

trait Trait {
    type Value;
    type Return: for<'a> ReturnKind<'a, Self::Value>;

    fn f<'a>(&'a self) -> <Self::Return as ReturnKind<'a, Self::Value>>::Type;
}

我们通过“调用”类型级函数ReturnKind来生成返回类型。

“输入参数”Return 需要实现 trait 以允许我们编写 &lt;Return as ReturnKind&lt;'a, Value&gt;&gt;。尽管我们不知道 Self 的确切生命周期是多少,但我们可以使用 HRTB Return: for&lt;'a&gt; ReturnKind&lt;'a, Value&gt; 使 Return 受 所有 可能的生命周期约束。

用法:

impl Trait for () {
    type Value = f64;
    type Return = Value;

    fn f(&self) -> f64 {
        42.0
    }
}

impl Trait for (f64,) {
    type Value = f64;
    type Return = Reference;

    fn f(&self) -> &f64 {
        &self.0
    }
}

fn main() {
    let a: (f64,) = ( ().f(), );
    let b: &f64 = a.f();
    println!("{:?} {:?}", a, b);
    // (42,) 42
}

请注意,上述方法仅适用于 Value 类型具有 'static 生命周期的情况。如果Value 本身的生命周期是有限的,那么Trait 必须知道这个生命周期。由于Rustdoesn't support associated lifetimes yet,它必须像Trait&lt;'foo&gt;一样使用,不幸的是:

struct Value;
struct Reference;
struct ExternalReference;

trait ReturnKind<'a, 's, T: ?Sized + 'a + 's> {
    type Type: ?Sized;
}
impl<'a, 's, T: ?Sized + 'a + 's> ReturnKind<'a, 's, T> for Value {
    type Type = T;
}
impl<'a, 's, T: ?Sized + 'a + 's> ReturnKind<'a, 's, T> for Reference {
    type Type = &'a T;
}
impl<'a, 's, T: ?Sized + 'a + 's> ReturnKind<'a, 's, T> for ExternalReference {
    type Type = &'s T;
}

trait Trait<'s> {
    type Value: 's;
    type Return: for<'a> ReturnKind<'a, 's, Self::Value>;

    fn f<'a>(&'a self) -> <Self::Return as ReturnKind<'a, 's, Self::Value>>::Type;
}

impl Trait<'static> for () {
    type Value = f64;
    type Return = Value;

    fn f(&self) -> f64 {
        42.0
    }
}

impl Trait<'static> for (f64,) {
    type Value = f64;
    type Return = Reference;

    fn f(&self) -> &f64 {
        &self.0
    }
}

impl<'a> Trait<'a> for (&'a f64,) {
    type Value = f64;
    type Return = ExternalReference;

    fn f(&self) -> &'a f64 {
        self.0
    }

}

fn main() {
    let a: (f64,) = ( ().f(), );
    let b: &f64 = a.f();
    let c: &f64 = (b,).f();
    println!("{:?} {:?} {:?}", a, b, c);
    // (42,) 42 42
}

但是如果在 trait 上有生命周期参数就可以了,那么 OP 已经提供了一个更简单的解决方案:

trait Trait<'a> {
    type Value;
    fn f<'b>(&'b self) -> Self::Value where 'b: 'a;
}

impl<'a> Trait<'a> for () {
    type Value = f64;
    fn f<'b: 'a>(&'b self) -> Self::Value {
        42.0
    }
}

impl<'a> Trait<'a> for (f64,) {
    type Value = &'a f64;
    fn f<'b: 'a>(&'b self) -> Self::Value {
        &self.0
    }
}
impl<'a, 's> Trait<'s> for (&'a f64,) {
    type Value = &'a f64;
    fn f<'b: 's>(&'b self) -> Self::Value {
        self.0
    }
}

fn main() {
    let a: (f64,) = ( ().f(), );
    let b: &f64 = a.f();
    let c: &f64 = (b,).f();
    println!("{:?} {:?} {:?}", a, b, c);
    // (42,) 42 42
}

【讨论】:

    【解决方案2】:

    @kennytm 提出了一个出色的(如果复杂的话)解决方案;我希望提出一个更简单的替代方案。

    有两种可能为值提供生命周期名称:

    • 在特质级别:trait Trait&lt;'a&gt; { ... }
    • 在方法级别:trait Trait { fn f&lt;'a&gt;(&amp;'a self) -&gt; ... }

    后者并没有被语言很好地支持,虽然更灵活但也相当复杂。但是,也经常发生前者就足够了。因此,我毫不犹豫地向您介绍:

    trait Trait<'a> {
        type Value;
        fn f(self) -> Self::Value;
    }
    

    f 消耗它的输出,如果 Self 是一个不可变引用,这很好,因为它们是 Copy。

    证据在布丁中:

    struct Type;
    
    impl Trait<'static> for () {
        type Value = Type;
        fn f(self) -> Self::Value {
            Type
        }
    }
    
    impl<'a> Trait<'a> for &'a (Type,) {
        type Value = &'a Type;
        fn f(self) -> Self::Value {
            &self.0
        }
    }
    

    并且可以毫无问题地调用它:

    fn main(){
       ().f();
       (Type,).f();
    }
    

    这个解决方案肯定没有那么灵活;但它也简单得多。

    【讨论】:

    • 感谢您的建议!老实说,我相信我更喜欢使用 trait Trait&lt;'a&gt; { type Value; fn f( &amp;'a self ) -&gt; Self::Value; } 的解决方案:它就像您所建议的那样使用 complex (在这两种情况下,任何使用该 trait 的东西都需要一个明确的生命周期)并且不不要消费Self,我更喜欢。无论如何,很高兴看到像这样的替代方案,它可能对其他用例更好。
    • @peoro:请注意,在为&amp;'a T 实现Trait 的情况下,消费self 无关紧要:&amp;'a T 是Copy。我会提防Trait&lt;'a&gt; { fn f(&amp;'a self) },您可能会不小心用它“固定”您的对象。请改用 kennytm 为 self 引入新生命周期的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-07
    • 2023-04-10
    • 1970-01-01
    • 2022-12-31
    • 1970-01-01
    相关资源
    最近更新 更多