Created
August 1, 2019 09:39
-
-
Save max6cn/e8df9f2a082a23c2e150a11d5afca264 to your computer and use it in GitHub Desktop.
Simple demo show how to use trait object for dynamic dispatch
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
#![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