Understanding Traits and Object Safety

前端 未结 2 1475
攒了一身酷
攒了一身酷 2020-11-29 12:19

I am struggling with the basics of object safety. If I have this code

struct S {
    x: i32
}

trait Trait: Sized {
    fn f(&self) -> i32 where Self:         


        
2条回答
  •  孤街浪徒
    2020-11-29 13:13

    Making Trait a supertype of Sized doesn't help - in fact it is not permitted, as the error message says. Each implementation of Trait will still have a different size, so your function object_safety_dynamic cannot be compiled. Monomorphization cannot be used here because there is no generic parameter, so the compiled function must work for all implementations of Trait.

    However, references do have a fixed size, so making the argument into a reference will work:

    trait Trait {
        fn f(&self) -> i32;
    }
    
    fn object_safety_dynamic(x: &Trait) {}
    

    A trait object is always a reference of some kind, e.g. a Box or &T. This is precisely because the size of implementations of the trait will be different, while a reference type has a known, fixed size.

提交回复
热议问题