Tutorial by Examples

Creating a Trait trait Speak { fn speak(&self) -> String; } Implementing a Trait struct Person; struct Dog; impl Speak for Person { fn speak(&self) -> String { String::from("Hello.") } } impl Speak for Dog { fn speak(&self) ->...
It is possible to create a function that accepts objects that implement a specific trait. Static Dispatch fn generic_speak<T: Speak>(speaker: &T) { println!("{0}", speaker.speak()); } fn main() { let person = Person {}; let dog = Dog {}; generic_speak(...
Use associated type when there is a one-to-one relationship between the type implementing the trait and the associated type. It is sometimes also known as the output type, since this is an item given to a type when we apply a trait to it. Creation trait GetItems { type First; // ^~~~ d...
trait Speak { fn speak(&self) -> String { String::from("Hi.") } } The method will be called by default except if it's overwritten in the impl block. struct Human; struct Cat; impl Speak for Human {} impl Speak for Cat { fn speak(&self) -> S...
When defining a new trait it is possible to enforce that types wishing to implement this trait verify a number of constraints or bounds. Taking an example from the standard library, the DerefMut trait requires that a type first implement its sibling Deref trait: pub trait DerefMut: Deref { fn...
It's also possible to add multiple object types to a Static Dispatch function. fn mammal_speak<T: Person + Dog>(mammal: &T) { println!("{0}", mammal.speak()); } fn main() { let person = Person {}; let dog = Dog {}; mammal_speak(&person); mammal...

Page 1 of 1