]> git.lizzy.rs Git - rust.git/blob - src/test/run-pass/class-cast-to-trait-multiple-types.rs
Replace all ~"" with "".to_owned()
[rust.git] / src / test / run-pass / class-cast-to-trait-multiple-types.rs
1 // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 #![feature(managed_boxes)]
12
13 trait noisy {
14   fn speak(&mut self) -> int;
15 }
16
17 struct dog {
18   barks: uint,
19
20   volume: int,
21 }
22
23 impl dog {
24     fn bark(&mut self) -> int {
25       println!("Woof {} {}", self.barks, self.volume);
26       self.barks += 1u;
27       if self.barks % 3u == 0u {
28           self.volume += 1;
29       }
30       if self.barks % 10u == 0u {
31           self.volume -= 2;
32       }
33       println!("Grrr {} {}", self.barks, self.volume);
34       self.volume
35     }
36 }
37
38 impl noisy for dog {
39     fn speak(&mut self) -> int {
40         self.bark()
41     }
42 }
43
44 fn dog() -> dog {
45     dog {
46         volume: 0,
47         barks: 0u
48     }
49 }
50
51 #[deriving(Clone)]
52 struct cat {
53   meows: uint,
54
55   how_hungry: int,
56   name: ~str,
57 }
58
59 impl noisy for cat {
60     fn speak(&mut self) -> int {
61         self.meow() as int
62     }
63 }
64
65 impl cat {
66     pub fn meow_count(&self) -> uint {
67         self.meows
68     }
69 }
70
71 impl cat {
72     fn meow(&mut self) -> uint {
73         println!("Meow");
74         self.meows += 1u;
75         if self.meows % 5u == 0u {
76             self.how_hungry += 1;
77         }
78         self.meows
79     }
80 }
81
82 fn cat(in_x: uint, in_y: int, in_name: ~str) -> cat {
83     cat {
84         meows: in_x,
85         how_hungry: in_y,
86         name: in_name
87     }
88 }
89
90
91 fn annoy_neighbors(critter: &mut noisy) {
92     for _i in range(0u, 10) { critter.speak(); }
93 }
94
95 pub fn main() {
96   let mut nyan: cat = cat(0u, 2, "nyan".to_owned());
97   let mut whitefang: dog = dog();
98   annoy_neighbors(&mut nyan);
99   annoy_neighbors(&mut whitefang);
100   assert_eq!(nyan.meow_count(), 10u);
101   assert_eq!(whitefang.volume, 1);
102 }