Skip to content

Instantly share code, notes, and snippets.

@335g
Created March 31, 2018 09:42
Show Gist options
  • Save 335g/42f61a8ca0fbb845e134db675d13cc7b to your computer and use it in GitHub Desktop.
Save 335g/42f61a8ca0fbb845e134db675d13cc7b to your computer and use it in GitHub Desktop.
type erasure in rust
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