]> git.lizzy.rs Git - rust.git/blob - src/test/run-pass/class-cast-to-trait-multiple-types.rs
auto merge of #9608 : hmarr/rust/vec-get-opt, r=huonw
[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 trait noisy {
12   fn speak(&self) -> int;
13 }
14
15 struct dog {
16   priv barks : @mut uint,
17
18   volume : @mut int,
19 }
20
21 impl dog {
22     fn bark(&self) -> int {
23       info2!("Woof {} {}", *self.barks, *self.volume);
24       *self.barks += 1u;
25       if *self.barks % 3u == 0u {
26           *self.volume += 1;
27       }
28       if *self.barks % 10u == 0u {
29           *self.volume -= 2;
30       }
31       info2!("Grrr {} {}", *self.barks, *self.volume);
32       *self.volume
33     }
34 }
35
36 impl noisy for dog {
37   fn speak(&self) -> int { self.bark() }
38 }
39
40 fn dog() -> dog {
41     dog {
42         volume: @mut 0,
43         barks: @mut 0u
44     }
45 }
46
47 #[deriving(Clone)]
48 struct cat {
49   priv meows : @mut uint,
50
51   how_hungry : @mut int,
52   name : ~str,
53 }
54
55 impl noisy for cat {
56   fn speak(&self) -> int { self.meow() as int }
57 }
58
59 impl cat {
60   pub fn meow_count(&self) -> uint { *self.meows }
61 }
62
63 impl cat {
64     fn meow(&self) -> uint {
65       info2!("Meow");
66       *self.meows += 1u;
67       if *self.meows % 5u == 0u {
68           *self.how_hungry += 1;
69       }
70       *self.meows
71     }
72 }
73
74 fn cat(in_x : uint, in_y : int, in_name: ~str) -> cat {
75     cat {
76         meows: @mut in_x,
77         how_hungry: @mut in_y,
78         name: in_name
79     }
80 }
81
82
83 fn annoy_neighbors(critter: @noisy) {
84     for _i in range(0u, 10) { critter.speak(); }
85 }
86
87 pub fn main() {
88   let nyan : cat  = cat(0u, 2, ~"nyan");
89   let whitefang : dog = dog();
90   annoy_neighbors(@nyan.clone() as @noisy);
91   annoy_neighbors(@whitefang as @noisy);
92   assert_eq!(nyan.meow_count(), 10u);
93   assert_eq!(*whitefang.volume, 1);
94 }