【问题标题】:Can I define a trait that has a generic function returning a trait object?我可以定义一个具有返回特征对象的通用函数的特征吗?
【发布时间】:2021-08-17 22:54:02
【问题描述】:

是否有可能有一个返回任何特征对象的特征函数?

或者,泛型参数可以是特征对象类型吗?

trait ToVec<T> {
    fn to_vec(&self) -> Vec<&dyn T>;
}

trait TraitA {}
trait TraitB {}
// etc

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=92008c3e799f9c2f9189a0100daa4e1a

【问题讨论】:

    标签: rust


    【解决方案1】:

    你不能拥有&amp;dyn T,因为T 不是特征。但是&amp;dyn ToVec&lt;T&gt;(或&amp;dyn SomeOtherTrait)没问题。

    在您的操场示例中,Vec&lt;T&gt; 实际上是正确的,因为您在 impls 中已经将 T 作为特征对象 &amp;dyn TraitA;但正如错误消息所说,您需要修复生命周期。例如。 this compiles

    trait TraitA {}
    
    trait ToVec<T> {
        fn to_vec(&self) -> Vec<T>;
    }
    
    impl<'a, T: TraitA> ToVec<&'a dyn TraitA> for (&'a str, &'a T) {
        fn to_vec(&self) -> Vec<&'a dyn TraitA> {
            vec![
                self.1 as &dyn TraitA
            ]
        }
    }
    

    但可能是也可能不是你想要的。

    【讨论】:

    • 您的链接是错误的,仅供参考,看起来您复制了原始链接并且没有生成新链接。
    • @loganfsmyth 已修复,谢谢(一定假设它会在编辑后重新生成...)。
    猜你喜欢
    • 1970-01-01
    • 2020-03-30
    • 2014-01-09
    • 2017-06-17
    • 2013-10-30
    • 2022-10-07
    • 1970-01-01
    • 2018-02-14
    • 1970-01-01
    相关资源
    最近更新 更多