Skip to content

Instantly share code, notes, and snippets.

@max6cn
Created August 1, 2019 09:39
Show Gist options
  • Save max6cn/e8df9f2a082a23c2e150a11d5afca264 to your computer and use it in GitHub Desktop.
Save max6cn/e8df9f2a082a23c2e150a11d5afca264 to your computer and use it in GitHub Desktop.
Simple demo show how to use trait object for dynamic dispatch
#![allow(dead_code)]
trait Bar {
fn bar(&self) -> i32;
}
struct Foo{
i:i32
}
impl Bar for Foo {
fn bar(&self) -> i32{
self.i
}
}
fn baz ( t: Box<&dyn Bar>) -> i32 {
t.bar() + 1
}
#[test]
fn test() {
let foo = Foo{ i : 10};
assert_eq!(10, foo.i);
let d :&dyn Bar = &foo;
let v1 = d.bar();
let x = Box::new(d);
let v2 = baz(x);
assert_eq!(v1,10);
assert_eq!(v2,11);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment