Skip to content

Instantly share code, notes, and snippets.

@dataf3l
Created July 25, 2019 12:05
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 dataf3l/563170d23afb5bf73ba0fb6547d5923b to your computer and use it in GitHub Desktop.
Save dataf3l/563170d23afb5bf73ba0fb6547d5923b to your computer and use it in GitHub Desktop.
trait Foo {
fn method(&self) -> String;
}
struct S1 {
a: u8,
}
struct S2 {
a: String,
}
impl Foo for S1 {
fn method(&self) -> String { format!("u8: {}", self.a) }
}
impl Foo for S2 {
fn method(&self) -> String { format!("string: {}", self.a) }
}
fn do_something(x: &Box<dyn Foo>) {
println!("{}",x.method());
}
fn main() {
//let x = &S1{a:5u8};
//let y = &S2{a:"Hello".to_string()};
let list_of_foo:Vec<Box<dyn Foo>> = vec![
Box::new(S1{a:5u8}),
Box::new(S2{a:"Hello".to_string()})];
for i in list_of_foo.iter() {
do_something(i);
}
println!("Hello, world!");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment