Rust traits: Difference between revisions

From wikinotes
(Created page with "Traits are similar to interfaces except they can have a default implementation. = Basics = <blockquote> <syntaxhighlight lang="rust"> </syntaxhighlight> </blockquote><!-- Basics -->")
 
Line 4: Line 4:
<blockquote>
<blockquote>
<syntaxhighlight lang="rust">
<syntaxhighlight lang="rust">
struct Cat { name: String }
struct Dog { name: String, breed: String }


trait Pet {
    fn play(&self);
}
impl Pet for Cat {
    fn play(&self) {
        println!("you give a ball of yarn to {}", self.name)
    }
}
impl Pet for Dog {
    fn play(&self) {
        println!("you throw a stick for {}", self.name)
    }
}
fn play_with_pet(pet: &impl Pet) {
    pet.play();
}
fn main(){
    let cat = Cat{name: "maize".to_string()};
    let dog = Dog{name: "midnight".to_string(), breed: "?".to_string()};
    play_with_pet(&cat);
    play_with_pet(&dog);
}
</syntaxhighlight>
</syntaxhighlight>
</blockquote><!-- Basics -->
</blockquote><!-- Basics -->

Revision as of 19:49, 8 February 2023

Traits are similar to interfaces except they can have a default implementation.

Basics

struct Cat { name: String }
struct Dog { name: String, breed: String }

trait Pet {
    fn play(&self);
}


impl Pet for Cat {
    fn play(&self) {
        println!("you give a ball of yarn to {}", self.name)
    }
}


impl Pet for Dog {
    fn play(&self) {
        println!("you throw a stick for {}", self.name)
    }
}

fn play_with_pet(pet: &impl Pet) {
    pet.play();
}

fn main(){
    let cat = Cat{name: "maize".to_string()};
    let dog = Dog{name: "midnight".to_string(), breed: "?".to_string()};
    play_with_pet(&cat);
    play_with_pet(&dog);
}