Traits Intro

View saved

Define and implement a trait

A trait lists method signatures. Types opt in with impl Trait for Type.

trait Greet {
    fn greet(&self) -> String;
}

struct Person { name: String }

impl Greet for Person {
    fn greet(&self) -> String {
        format!("Hi, {}", self.name)
    }
}

Use trait bounds

Generic functions can require that T implements a trait.

fn print_greet<T: Greet>(value: &T) {
    println!("{}", value.greet());
}

Common standard traits

  • Debug for formatting with {:?}
  • Clone for explicit copies
  • Display for user-facing text
  • From/Into for conversions

Derive when possible

Many traits can be auto-implemented.

#[derive(Debug, Clone)]
struct Point { x: i32, y: i32 }

Comments

One comment per signed-in account. Comments are saved with this page’s URL.