Skip to content

Instantly share code, notes, and snippets.

@Nemikolh
Created December 11, 2014 10:34
Show Gist options
  • Save Nemikolh/806308a894c87dd21263 to your computer and use it in GitHub Desktop.
Save Nemikolh/806308a894c87dd21263 to your computer and use it in GitHub Desktop.
Rust dynamic dispatch vs static dispatch
trait Test {
fn toto(&self) -> String;
}
impl Test for uint {
fn toto(&self) -> String {
"uint".to_string()
}
}
impl Test for int {
fn toto(&self) -> String {
"int".to_string()
}
}
fn print_toto_dynamic(value: &Test) {
println!("{}", value.toto());
}
fn print_toto_static<T: Test>(value: T) {
println!("{}", value.toto());
}
// This code is editable and runnable!
fn main() {
print_toto_dynamic(&1u);
print_toto_dynamic(&1i);
print_toto_static(1u);
print_toto_static(1i);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment