Skip to content

Instantly share code, notes, and snippets.

@grahamking
Created January 31, 2021 04:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save grahamking/8c6849bdc01531988413a8f2c1ec920b to your computer and use it in GitHub Desktop.
Save grahamking/8c6849bdc01531988413a8f2c1ec920b to your computer and use it in GitHub Desktop.
trait Nameable<T> {
fn set_name(&mut self, T);
}
struct Cyborg{
name: Option<String>,
}
impl Nameable<&str> for Cyborg {
fn set_name(&mut self, s: &str) {
self.name = Some(s.to_string());
}
}
impl Nameable<usize> for Cyborg {
fn set_name(&mut self, serial_number: usize) {
self.name = Some(serial_number.to_string());
}
}
fn main() {
let mut mostly_human = Cyborg{name: None};
mostly_human.set_name("Bob");
let mut mostly_machine = Cyborg{name: None};
mostly_machine.set_name(2077);
println!("{} vs {}",
mostly_human.name.unwrap(),
mostly_machine.name.unwrap(),
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment