【问题标题】:Why does a reference to a trait in a generic function have to implement `Sized`?为什么泛型函数中对特征的引用必须实现“Sized”?
【发布时间】:2017-06-03 22:30:20
【问题描述】:

我有一个函数返回对 trait (trait_ref()) 的引用,另一个函数返回对通用 trait 实现 (take_trait_ref_generic) 的引用。

但是,无法将我从第一个函数获得的引用传递给第二个函数。 Rustc 抱怨“std::marker::Sized 的 trait 没有为 SomeTrait 实现”。

即使是这样,为什么还要实现Sized?反正是个参考。

trait SomeTrait {}

struct TraitImpl;

impl SomeTrait for TraitImpl {}

struct Container {
    trait_impl: TraitImpl,
}

impl Container {
    fn trait_ref(&self) -> &SomeTrait {
        &self.trait_impl
    }
}

fn take_trait_ref_generic<T: SomeTrait>(generic_trait_ref: &T) {}

fn main() {
    let container = Container { trait_impl: TraitImpl };

    /*Not possible*/
    take_trait_ref_generic(container.trait_ref());
}

【问题讨论】:

    标签: reference rust traits


    【解决方案1】:

    默认情况下,函数上的 所有 泛型类型隐含地具有 Sized 绑定,无论它们如何使用。您需要使用 ?Sized 明确选择退出该要求:

    fn take_trait_ref_generic<T>(generic_trait_ref: &T)
    where 
        T: ?Sized + SomeTrait
    {}
    

    【讨论】:

    • 好的,这条规则有充分的理由吗?换句话说,如果编译器自动添加 +?Sized 仅在引用中使用的所有边界,我们会失去什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-29
    • 2015-09-05
    • 2021-07-02
    • 1970-01-01
    相关资源
    最近更新 更多