What are object safe traits in Rust?
Object-safe traits are traits with methods that follow these two rules:
- the return type is not
Self - there are no generic types parameters
Selfis 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.
Example
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
Copyright ©2025 Educative, Inc. All rights reserved