Rust traits: Difference between revisions

From wikinotes
Line 3: Line 3:
= Basics =
= Basics =
<blockquote>
<blockquote>
Define and implement trait
<syntaxhighlight lang="rust">
<syntaxhighlight lang="rust">
struct Cat { name: String }
struct Cat { name: String }
Line 20: Line 21:
</syntaxhighlight>
</syntaxhighlight>


Use trait implementors in method signature
<syntaxhighlight lang="rust">
<syntaxhighlight lang="rust">
// use trait as param type
// use trait as param type
Line 26: Line 28:
}
}


fn main(){
let cat = Cat{name: "maize".to_string()};
    let cat = Cat{name: "maize".to_string()};
let dog = Dog{name: "midnight".to_string(), breed: "?".to_string()};
    let dog = Dog{name: "midnight".to_string(), breed: "?".to_string()};
play_with_pet(&cat);
    play_with_pet(&cat);
play_with_pet(&dog);
    play_with_pet(&dog);
}
</syntaxhighlight>
</syntaxhighlight>
</blockquote><!-- Basics -->
</blockquote><!-- Basics -->

Revision as of 19:53, 8 February 2023

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

Basics

Define and implement trait

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

// all implementors of 'Pet' must have method 'play' with this method signature
trait Pet {
    fn play(&self);
}


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

Use trait implementors in method signature

// use trait as param type
fn play_with_pet(pet: &impl Pet) {
    pet.play();
}

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);