3 ms·
It has to do with type erasure and knowing how big a type is in memory, not mutation. With traits, you can erase the implementing type and get back a vtable of
by throwup238 2y ago
It has to do with type erasure and knowing how big a type is in memory, not mutation. With traits, you can erase the implementing type and get back a vtable of a trait's method - called a trait object.
A trait is object-safe as long as no trait method returns the implementing type (like T::clone() -> T). Once it's a trait object, T is no longer known and the compiler doesn't know how much memory to allocate on the stack or heap, which makes it impossible to use. That's why trait objects have to be boxed or behind references - all pointers have a known size.
- diarrhea 2y ago> A trait is object-safe as long as no trait method returns the implementing type (like T::clone() -> T) That, and much more: https://doc.rust-lang.org/reference/items/traits.html#object-safety https://doc.rust-lang.org/reference/items/traits.html#object... .
- asa400 2y agoThis is the shortest, clearest explanation I've yet seen of object safety. Thanks.