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