Home > Mobile >  what's the purpose of `impl Foo for Foo`?
what's the purpose of `impl Foo for Foo`?

Time:10-20

I am looking for the answer why a sized trait is not object safe, for example:

trait Foo:Sized{}

Foo is not object safe.

I have read some posts about object safey, like object-safety and sizedness-in-rust. I find the deep reason is compiler automatically impl Foo for Foo.

I confuse why compiler do this and why this cause Foo not object safe?

Thank you very much.

CodePudding user response:

impl Foo for Foo is the way to write in Rust "implement trait Foo for trait object Foo". A trait can be only object-safe if the trait object for this trait implements the trait. Obviously, there is no much sense having a trait object, that does not implement itself.

By specifying trait Foo : Sized {}, you require that all implementors of Foo must also implement Sized. But all trait objects in Rust are ?Sized, meaning they can be unsized. Thus the trait object for type Foo : Sized cannot implement Foo, so you cannot write

impl Foo for Foo

or, in other words, the trait is not object safe.

  • Related