Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

rust
object
trait

What are object safe traits in Rust?

Educative Answers Team

Object-safe traits are traits with methods that follow these two rules:

  • the return type is not Self
  • there are no generic types parameters

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 shot.

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 left 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.

RELATED TAGS

rust
object
trait
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring