Learn Before
Code

Example of Trait - Rust Programming

// Define a trait named `Speak` // with a single method `speak`. trait Speak { fn speak(&self); } // Define a struct named `Human`. struct Human { name: String, } // Implement the `Speak` trait for the `Human` struct. impl Speak for Human { fn speak(&self) { println!("Hello, my name is {}.", self.name); } } // Define a struct named `Dog`. struct Dog { name: String, } // Implement the `Speak` trait for the `Dog` struct. impl Speak for Dog { fn speak(&self) { println!("Woof! My name is {}.", self.name); } } fn main() { // Create instances of `Human` and `Dog`. let person = Human { name: String::from("Alice"), }; let dog = Dog { name: String::from("Buddy"), }; // Call the `speak` method, which is // implemented via the `Speak` trait. person.speak(); dog.speak(); // Alternatively, use a function that takes // a reference to a `Speak` trait object. introduce_speaker(&person); introduce_speaker(&dog); } fn introduce_speaker(speaker: &dyn Speak) { speaker.speak(); }

0

1

Updated 2023-04-20

Tags

Object-Oriented Programming

Programming Language Paradigms

General programming languages

Computing Sciences