links: Object Safety

Object safety is an important concept in Rust when working with trait objects. A trait is considered object safe if it meets certain criteria that allow it to be used as a trait object, enabling polymorphism. Here’s a summary of the key points on object safety from the official Rust documentation:

Key Points on Object Safety

  1. Definition:

  2. Object Safety Rules:

  3. Receiver Types:

  4. Examples of Object-Safe Traits:

    trait ObjectSafe {
        fn foo(&self);
        fn bar(&mut self);
        fn baz(self: Box<Self>);
    }
    
  5. Non-Object-Safe Traits:

    trait NotObjectSafe {
        fn foo(&self) -> Self; // Returns Self
        fn bar<T>(&self, x: T); // Has generic parameters
    }
    

Practical Implications

Summary

Object safety ensures that traits can be turned into trait objects, enabling dynamic dispatch. The key rules are avoiding Self in method signatures (except as a receiver), not having generic methods, and ensuring the trait does not require Self: Sized. These constraints are crucial for enabling polymorphism in Rust.

For a more detailed explanation and examples, refer to the official Rust documentation on object safety.