Last active
December 5, 2017 20:27
-
-
Save asonix/1a350a1e50c504b08c3fc7297a34a129 to your computer and use it in GitHub Desktop.
Example of using traits with structs
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
trait HasAStringInIt { | |
fn get_str(&self) -> &str; | |
fn set_str(&mut self, new_string: String); | |
} | |
struct File { | |
name: String, | |
contents: Vec<u8>, | |
} | |
impl HasAStringInIt for File { | |
fn get_str(&self) -> &str { | |
&self.name | |
} | |
fn set_str(&mut self, new_string: String) { | |
self.name = new_string; | |
} | |
} | |
struct Message { | |
from: User, | |
contents: String, | |
} | |
impl HasAStringInIt for Message { | |
fn get_str(&self) -> &str { | |
&self.contents | |
} | |
fn set_str(&mut self, new_string: String) { | |
self.contents = new_string; | |
} | |
} | |
struct User { | |
username: String, | |
} | |
impl HasAStringInIt for User { | |
fn get_str(&self) -> &str { | |
&self.username | |
} | |
fn set_str(&mut self, new_string: String) { | |
self.username = new_string; | |
} | |
} | |
struct Person { | |
name: String, | |
age: u32, | |
} | |
impl HasAStringInIt for Person { | |
fn get_str(&self) -> &str { | |
&self.name | |
} | |
fn set_str(&mut self, new_string: String) { | |
self.name = new_string; | |
} | |
} | |
fn print_has_a_string_in_it<T>(has_a_string_in_it: &T) | |
where | |
T: HasAStringInIt, | |
{ | |
println!("There is a string here: {}", has_a_string_in_it.get_str()); | |
} | |
fn main() { | |
let file = File { | |
name: "Woah".into(), | |
contents: Vec::new(), | |
}; | |
let message = Message { | |
from: User { username: "jingle.dog".into() }, | |
contents: "Blep".into(), | |
}; | |
let user = User { username: "asonix".into() }; | |
let person = Person { | |
name: "Arlo".into(), | |
age: 20, | |
}; | |
print_has_a_string_in_it(&file); | |
print_has_a_string_in_it(&message); | |
print_has_a_string_in_it(&user); | |
print_has_a_string_in_it(&person); | |
// make file mutable so we can change it | |
let mut file = file; | |
file.set_str("I gave this file a new name".into()); | |
print_has_a_string_in_it(&file); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment