Object safety is a set of rules and restrictions that does not allow trait objects to be constructed. Consider the following code:
// object_safety.rs
trait Foo {
fn foo();
}
fn generic(val: &Foo) {
}
fn main() {
}
We get the following error upon compilation:
This brings us to the idea of object safety, which is a set of restrictions that forbids creating a trait object from a trait. In this example, since our type doesn't have a self reference, it's not possible to create a trait object out of it. In this case, to convert any type into a trait object, methods on the type need to be an instance—one that takes self by reference. So, we change our trait method declaration, foo, to the following:
trait Foo {
fn foo(&self);
}
This makes the the compiler happy.