Why does a reference to a trait in a generic function have to implement `Sized`?

百般思念 提交于 2019-12-17 19:54:54

问题


I have a function that returns a reference to a trait (trait_ref()) and another function that takes a reference to a generic trait implementation (take_trait_ref_generic).

However, it's not possible to pass the reference I get from the first function to the second one. Rustc complains that "the trait std::marker::Sized is not implemented for SomeTrait".

Even though that's true, why does it have to implement Sized? It's a reference anyway.

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());
}

回答1:


By default, all generic types on functions implicitly have the Sized bound, regardless of how they are used. You need to explicitly opt-out of that requirement using ?Sized:

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


来源:https://stackoverflow.com/questions/44343818/why-does-a-reference-to-a-trait-in-a-generic-function-have-to-implement-sized

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!