Understanding Traits and Object Safety

Viewed 4324

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: Sized;
}

fn object_safety_dynamic(x: Trait) {}

I receive

error[E0038]: the trait `Trait` cannot be made into an object
  --> src/lib.rs:11:29
   |
5  | trait Trait: Sized {
   |       -----  ----- ...because it requires `Self: Sized`
   |       |
   |       this trait cannot be made into an object...
...
11 | fn object_safety_dynamic(x: Trait) {}
   |                             ^^^^^ the trait `Trait` cannot be made into an object

When I add or remove : Sized as the supertrait or as f's bound, I receive slightly different error messages.

Could someone explain:

  • Why does this particular example not work? The chapter Trait Objects states:

    So what makes a method object-safe? Each method must require that Self: Sized

    Isn't that fulfilled?

  • What is the difference between Trait: Sized and where Self: Sized? (Well, yes, one inherits the trait and the other one is a parameter bound, but from Rust's trait object perspective?

  • What is the preferred change I had to make object_safety_dynamic work?

I am using rustc 1.19.0-nightly (01951a61a 2017-05-20) if it matters.

Addressing the comment on fixed sizes.

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

    fn g<T>(&self, t: T) -> i32
    where
        Self: Sized;
}
2 Answers
Related