1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2024-12-17 15:21:32 +02:00
comprehensive-rust/src/traits.md
rbehjati 739b3a01e0
Restructure Day-3 morning (#503)
* Restructure Day-3 morning
2023-03-30 13:25:34 +01:00

638 B

Traits

Rust lets you abstract over types with traits. They're similar to interfaces:

trait Pet {
    fn name(&self) -> String;
}

struct Dog {
    name: String,
}

struct Cat;

impl Pet for Dog {
    fn name(&self) -> String {
        self.name.clone()
    }
}

impl Pet for Cat {
    fn name(&self) -> String {
        String::from("The cat") // No name, cats won't respond to it anyway.
    }
}

fn greet<P: Pet>(pet: &P) {
    println!("Who's a cutie? {} is!", pet.name());
}

fn main() {
    let fido = Dog { name: "Fido".into() };
    greet(&fido);

    let captain_floof = Cat;
    greet(&captain_floof);
}