Last active
April 13, 2018 16:29
-
-
Save ryochack/3f9f6ef38e41cf5b54b7d0c426c9abea 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
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