Last active
October 16, 2020 08:12
-
-
Save swallez/524057bcc33ea47ddefad9f0b31146e3 to your computer and use it in GitHub Desktop.
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
// Example of static methods in Rust traits, to illustrate this tweet: | |
// https://twitter.com/bluxte/status/1316315285356531712 | |
// | |
// Try it in the Rust playground at | |
// https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=524057bcc33ea47ddefad9f0b31146e3 | |
/// Something that has a name and can say it | |
trait NamedThing { | |
/// Static method | |
fn new(name: String) -> Self; | |
/// Object method | |
fn say_my_name(&self); | |
} | |
/// A soft spoken person | |
struct Whisperer { | |
name: String | |
} | |
impl NamedThing for Whisperer { | |
fn new(name: String) -> Self { | |
// Same as `return Whisperer{name};` | |
Whisperer{name} | |
} | |
fn say_my_name(&self) { | |
println!("My name is {}", self.name.to_lowercase()) | |
} | |
} | |
/// A loud person | |
struct Yeller { | |
name: String | |
} | |
impl NamedThing for Yeller { | |
fn new(name: String) -> Self { | |
Yeller{name} | |
} | |
fn say_my_name(&self) { | |
println!("MY NAME IS {}", self.name.to_uppercase()) | |
} | |
} | |
/// From a NamedThing type and a name, create a thing and say its name | |
fn create_and_say_name<T: NamedThing> (name: String) -> T { | |
// Constructor function to call depends on the type | |
let thing = T::new(name); | |
thing.say_my_name(); | |
thing | |
} | |
fn main() { | |
// Type is inferred from the variable type | |
let _whisperer: Whisperer = create_and_say_name("Joe".into()); | |
// We can also explicitely provide generic parameters | |
let _yeller = create_and_say_name::<Yeller>("Jack".into()); | |
} | |
// Output: | |
// My name is joe | |
// MY NAME IS JACK |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment