Rust Traits
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct Person { | |
id: i32, | |
title: String | |
} | |
impl Person { | |
fn new(id: i32, title: &str) -> Person { | |
Person { | |
id: id, | |
title: title.to_string() | |
} | |
} | |
} | |
trait HasId { | |
fn id(&self) -> i32; | |
} | |
trait HasTitle { | |
fn title(&self) -> &str; | |
} | |
impl HasId for Person { | |
fn id(&self) -> i32 { | |
self.id | |
} | |
} | |
impl HasTitle for Person { | |
fn title(&self) -> &str { | |
&self.title | |
} | |
} | |
fn main() { | |
let person = Person::new(1, "Jan"); | |
println!("{}: {}", person.id(), person.title()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment