简体   繁体   中英

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

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

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
{}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM