Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- struct Dog {
- name: &'static str
- }
- trait Animal : Noisy {
- fn Run(&self);
- }
- trait Noisy {
- fn Noise(&self) -> String;
- }
- trait Threat : Animal {
- fn EatHuman(&self) ->String;
- }
- impl Animal for Dog {
- fn Run(&self) { println!("On all fours, and wagging tail.")}
- }
- struct WildDog {
- dog:Dog
- }
- impl Animal for WildDog
- {
- fn Run(&self) { println!("On all fours, and nose low.")}
- }
- impl Noisy for Dog {
- fn Noise(&self) -> String {
- return String::from("Bark!");
- }
- }
- impl Noisy for WildDog{
- fn Noise(&self) -> String {
- return String::from("Yelp!");
- }
- }
- impl Threat for WildDog
- {
- fn EatHuman(&self) -> String{
- return String::from("On all fours, and nose low.");
- }
- }
- fn main() {
- // Type annotation is necessary in this case.
- let dolly = Dog{name: "Dolly"};
- // TODO ^ Try removing the type annotations.
- GoToThePark(&dolly);
- MeTryingToSleep(&dolly);
- let c = WildDog{ dog: Dog{name: "Stephan"}};
- GoToThePark(&c);
- MeTryingToSleep(&c);
- BeScared(&c);
- }
- fn GoToThePark<T: Animal>(x: &T) {
- println!("++++++++\nMe going to the park\n++++++++\n");
- x.Run();
- println!("{}",x.Noise())
- }
- fn MeTryingToSleep<T: Noisy>(x : &T) {
- println!("++++++++\nMe trying to sleep\n++++++++\n");
- println!("{}",x.Noise())
- }
- fn BeScared<T :Threat>(x : &T) {
- println!("++++++++\nMe being scared\n++++++++\n");
- GoToThePark(x);
- println!("{}",x.EatHuman())
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement