Object safety determines if a Rust trait can be used for dynamic dispatch via trait objects like `dyn Trait`.
Object safety in Rust means a trait can be used to create a trait object (dyn Trait) only if all its methods have a known size and no generic type parameters that prevent dynamic dispatch. If a trait is not object-safe, you cannot use it with dyn for runtime polymorphism.
// Object-safe trait: can be used as `dyn Shape`
trait Shape {
fn area(&self) -> f64;
}
// Not object-safe: generic method prevents `dyn GenericTrait`
trait GenericTrait {
fn process<T>(&self, item: T);
}
Object safety is a rule that decides if a set of behaviors (a trait) can be used to handle different types of objects at runtime. It matters because it allows you to write flexible code that treats different items as the same thing without knowing their exact type beforehand. Think of it like a universal remote: it only works if every button on the remote has a standard function that fits any TV, not a custom button that only works on one specific model.