Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

A trait represents a functionality. It defines a list of one or more methods that a type must implement in order to provide this functionality.

In Rust, almost any data type can implement a trait:

Inside the standard library:

A list of the most common traits of the standard library is available in Table 1. Among them are the comparison operators from the cmp module. Other operators (*, /, +, %, ...) are defined inside the ops module. They are listed inside the ops traits section.

Table 1:Some of the most common traits

Trait

Description

Clone

To make a object clonable.

Copy

Reserved for copiable types.

Debug

To provide the Debug formatter.

Display

To provide the Display formatter.

Default

To set a default value for a type.

Eq

Like PartialEq plus reflexivity (a == a).

Ord

Like PartialOrd plus min(), max() and clamp().

PartialEq

To provide operators == and !=.

PartialOrd

To provide operators <, <=, > and >=.

20.1.1Defining a trait

As an example we want to create a trait Surface that defines a method for computing the area. We will use this trait for a structure Rectangle.

Here is the Rectangle structure:

And an instance of that structure:

To define a custom trait, we use the trait keyword. At least one method must be defined, and only its declaration (i.e.: function’s header, without a body) is necessary. In the following example, we define the trait Surface with its method area():

To implement the trait for our structure, we use the impl keyword in its form impl <trait> for <struct>:

The area() method is now available for our rect object:

68.4