0
0
Rustprogramming~5 mins

Implementing traits in Rust

Choose your learning style9 modes available
Introduction

Traits let you define shared behavior that different types can use. Implementing traits means making your types follow these shared rules.

You want different types to have the same kind of behavior, like printing or comparing.
You want to write functions that can work with many types that share some behavior.
You want to add new abilities to your own types.
You want to organize code by grouping related functions together.
You want to use polymorphism to handle different types in a uniform way.
Syntax
Rust
impl TraitName for TypeName {
    // define required methods here
}

You write impl TraitName for TypeName to say your type uses that trait.

Inside the braces, you write the functions the trait needs.

Examples
This example shows a trait Greet with one method. The struct Person implements it by printing a greeting.
Rust
trait Greet {
    fn greet(&self);
}

struct Person {
    name: String,
}

impl Greet for Person {
    fn greet(&self) {
        println!("Hello, {}!", self.name);
    }
}
Here, the trait Area requires a method that returns a number. The Circle struct implements it by calculating the circle's area.
Rust
trait Area {
    fn area(&self) -> f64;
}

struct Circle {
    radius: f64,
}

impl Area for Circle {
    fn area(&self) -> f64 {
        3.14159 * self.radius * self.radius
    }
}
Sample Program

This program defines a trait Describe with one method. The struct Book implements it to return a string describing the book. The main function creates a book and prints its description.

Rust
trait Describe {
    fn describe(&self) -> String;
}

struct Book {
    title: String,
    author: String,
}

impl Describe for Book {
    fn describe(&self) -> String {
        format!("{} by {}", self.title, self.author)
    }
}

fn main() {
    let book = Book {
        title: String::from("Rust Book"),
        author: String::from("Steve"),
    };
    println!("Description: {}", book.describe());
}
OutputSuccess
Important Notes

All methods required by the trait must be implemented.

You can implement multiple traits for one type.

Traits help write flexible and reusable code.

Summary

Traits define shared behavior that types can implement.

Use impl Trait for Type to add trait behavior to your types.

Implementing traits helps organize code and use polymorphism.