Skip to content

Instantly share code, notes, and snippets.

@munckymagik
Created December 5, 2019 21:05
Show Gist options
  • Save munckymagik/42296aa8051e981860b6380440bb9e75 to your computer and use it in GitHub Desktop.
Save munckymagik/42296aa8051e981860b6380440bb9e75 to your computer and use it in GitHub Desktop.
Constructors for concrete instances of a parameterized type
trait Animal {
fn make_sound(&self);
}
struct Dog {}
impl Animal for Dog {
fn make_sound(&self) {
println!("My signature bark!");
}
}
struct DogDouble {}
impl Animal for DogDouble {
fn make_sound(&self) {
println!("Quacks like a bark!");
}
}
struct Park<T: Animal> {
an_animal: T
}
impl<T: Animal> Park<T> {
// Doesn't compile
// fn with_a_dog() -> Self {
// let dog = Dog {};
// Self { an_animal: dog as T }
// }
fn provoke(&self) {
self.an_animal.make_sound();
}
}
// Implementation when T is a Dog
impl Park<Dog> {
fn with_a_dog() -> Self {
let dog = Dog {};
Self { an_animal: dog }
}
}
// Implementation when T is a DogDouble
impl Park<DogDouble> {
fn with_a_dog_double() -> Self {
let dog = DogDouble {};
Self { an_animal: dog }
}
}
fn main() {
let dog = Dog {};
let p = Park { an_animal: dog };
p.provoke();
let dog = DogDouble {};
let p = Park { an_animal: dog };
p.provoke();
let p = Park::with_a_dog();
p.provoke();
let p = Park::with_a_dog_double();
p.provoke();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment