0
0
Rustprogramming~7 mins

Defining traits in Rust

Choose your learning style9 modes available
Introduction

Traits let you define shared behavior that different types can use. It's like a promise that a type will have certain abilities.

When you want different types to have the same set of actions.
When you want to write code that works with many types in a similar way.
When you want to organize your code by grouping related functions.
When you want to add new behavior to types without changing their code.
Syntax
Rust
trait TraitName {
    fn method_name(&self);
    // more methods
}

Traits are like interfaces in other languages.

Methods inside traits usually take &self to work with the instance.

Examples
This trait requires a method say_hello that prints a greeting.
Rust
trait Speak {
    fn say_hello(&self);
}
This trait requires a method area that returns a number.
Rust
trait Area {
    fn area(&self) -> f64;
}
Sample Program

This program defines a trait Speak with a method say_hello. Both Dog and Cat implement this trait with their own greetings. The greet function accepts any type that implements Speak and calls say_hello.

Rust
trait Speak {
    fn say_hello(&self);
}

struct Dog;

impl Speak for Dog {
    fn say_hello(&self) {
        println!("Woof! Hello!");
    }
}

struct Cat;

impl Speak for Cat {
    fn say_hello(&self) {
        println!("Meow! Hello!");
    }
}

fn greet(animal: &impl Speak) {
    animal.say_hello();
}

fn main() {
    let dog = Dog;
    let cat = Cat;

    greet(&dog);
    greet(&cat);
}
OutputSuccess
Important Notes

Traits can have default method implementations.

You can implement multiple traits for one type.

Traits help write flexible and reusable code.

Summary

Traits define shared behavior for types.

Use traits to write code that works with many types.

Implement traits to give types specific abilities.