Created
March 31, 2018 09:42
-
-
Save 335g/42f61a8ca0fbb845e134db675d13cc7b to your computer and use it in GitHub Desktop.
type erasure in rust
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 AnimalExt { | |
fn eat(&self, food: String); | |
} | |
struct Dog; | |
impl AnimalExt for Dog { | |
fn eat(&self, food: String) { | |
println!("dog: {:?}", food); | |
} | |
} | |
struct AnyAnimal { | |
eat: Box<Fn(String)>, | |
} | |
impl AnyAnimal { | |
fn new<A>(animal: A) -> Self | |
where | |
A: AnimalExt + 'static, | |
{ | |
AnyAnimal { | |
eat: Box::new(move |s| animal.eat(s)) | |
} | |
} | |
} | |
impl AnimalExt for AnyAnimal { | |
fn eat(&self, food: String) { | |
(self.eat)(food); // ok | |
// self.eat(food) <- fatal runtime error: stack overflow | |
} | |
} | |
fn main() { | |
let a = AnyAnimal::new(Dog); | |
a.eat("aaa".to_string()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment