rust / beginner
Snippet
Basic Trait Definitions
Traits define shared behavior that types can implement. They act like interfaces in other languages. The greet method takes self and returns a String. Types implement traits using impl Trait for Type syntax.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
trait Greeting {fn greet(&self) -> String;}struct Person {name: String,}impl Greeting for Person {fn greet(&self) -> String {format!("Hello, {}!", self.name)}}fn main() {let person = Person { name: String::from("Anna") };println!("{} ", person.greet());}
Breakdown
1
trait Greeting { fn greet(&self) -> String; }
Defines a trait with one method signature
2
impl Greeting for Person { ... }
Implements the trait for the Person struct