Object-safe traits are traits with methods that follow these two rules:
Self
Self
is an alias for the type we will be implementing the trait on.
Only object-safe traits can be made into trait objects. To learn more about creating trait objects, check out this answer.
Below are two examples of traits, one that is object-safe and one that is not.
An object-safe trait
pub trait Area {
/// Returns area as i32 (32-bit
/// integer)
fn area(&self) -> i32;
}
Not an object-safe trait
pub trait Clone {
/// Returns a clone (duplicate)
/// of the object
fn clone(&self) -> Self;
}
The reason why the Clone
trait on the right is not object-safe is because the signature of its clone
method returns Self
.
For more details on why object-safety is required for trait objects, check out the official docs.
Free Resources