Skip to content

Instantly share code, notes, and snippets.

@ryochack
Last active April 13, 2018 16:29
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 ryochack/3f9f6ef38e41cf5b54b7d0c426c9abea to your computer and use it in GitHub Desktop.
Save ryochack/3f9f6ef38e41cf5b54b7d0c426c9abea to your computer and use it in GitHub Desktop.
trait Foo {
fn method(&self) -> String;
}
impl Foo for u8 {
fn method(&self) -> String {
format!("u8: {}", *self)
}
}
impl Foo for String {
fn method(&self) -> String {
format!("string: {}", *self)
}
}
// 静的ディスパッチ
fn do_static_dispatch<T: Foo>(x: &T) {
println!("{}", x.method());
}
// 動的ディスパッチ
fn do_dynamic_dispatch(x: &Foo) {
println!("{}", x.method());
}
fn main() {
let x = 5u8;
let y = "Hello".to_string();
do_static_dispatch(&x);
do_static_dispatch(&y);
do_dynamic_dispatch(&x);
do_dynamic_dispatch(&y);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment