Hacker News new | ask | show | jobs
by alilleybrinker 602 days ago
In part two, the author explains trait objects in a way that is, I think, a little misleading.

They're right that trait objects are dynamically sized types, which means they can't be passed by value to functions, but wrong that they need to be boxed; they can instead be put behind a reference. Both of the following are valid types.

  type DynFutureBox = Pin<Box<dyn Future<Output = ()>>>;
  type DynFutureRef<'f> = Pin<&'f dyn Future<Output = ()>>;
You can see this in the Rust Playground here: https://play.rust-lang.org/?version=stable&mode=debug&editio...
1 comments

Technically trait objects aren't entirely a thing at all. They're a concept that only makes sense in the concept of a pointer (references are safe pointers, `Box`es are smart pointers). You can refer to something as a trait object but the trait of the object is a property of the pointer and not the object. So if you have some struct that implements a trait you can cast a pointer to that struct to a pointer to a trait object, but that struct never stops being the struct, a trait object is just a different way of referring to the struct.
What about impl Trait then? In that case traits make sense without pointers.

To me traits are like a definition of capabilities. A way to duck type things.

"Trait objects" is lingo for `dyn Trait`. They are a distinct thing from just "trait". They allow virtual dispatch at runtime.

See https://doc.rust-lang.org/reference/types/trait-object.html (`dyn Trait`, runtime dynamic dispatch) vs https://doc.rust-lang.org/reference/types/impl-trait.html (`impl Trait`, compile-time monomorphization)

`impl Trait` is sort like of syntax sugar for generics (this is not the full story, for example TAIT/type_alias_impl_trait... but it's close enough). It's monomorphized just like generics are. If you have a method that takes an `impl Trait` then a new copy of the method will be emitted by the compiler for each unique type you pass to that `impl Trait` parameter.

Traits conceptually are kind of like definitions of capabilities. So you're not really wrong about that, that understanding probably may even help you.