]> git.proxmox.com Git - rustc.git/blob - src/test/run-pass/class-implement-traits.rs
Imported Upstream version 1.0.0~0alpha
[rustc.git] / src / test / run-pass / class-implement-traits.rs
1 // Copyright 2012-2014 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
12 trait noisy {
13 fn speak(&mut self);
14 }
15
16 #[derive(Clone)]
17 struct cat {
18 meows : uint,
19
20 how_hungry : int,
21 name : String,
22 }
23
24 impl cat {
25 fn meow(&mut self) {
26 println!("Meow");
27 self.meows += 1u;
28 if self.meows % 5u == 0u {
29 self.how_hungry += 1;
30 }
31 }
32 }
33
34 impl cat {
35 pub fn eat(&mut self) -> bool {
36 if self.how_hungry > 0 {
37 println!("OM NOM NOM");
38 self.how_hungry -= 2;
39 return true;
40 } else {
41 println!("Not hungry!");
42 return false;
43 }
44 }
45 }
46
47 impl noisy for cat {
48 fn speak(&mut self) { self.meow(); }
49 }
50
51 fn cat(in_x : uint, in_y : int, in_name: String) -> cat {
52 cat {
53 meows: in_x,
54 how_hungry: in_y,
55 name: in_name.clone()
56 }
57 }
58
59
60 fn make_speak<C:noisy>(mut c: C) {
61 c.speak();
62 }
63
64 pub fn main() {
65 let mut nyan = cat(0u, 2, "nyan".to_string());
66 nyan.eat();
67 assert!((!nyan.eat()));
68 for _ in range(1u, 10u) {
69 make_speak(nyan.clone());
70 }
71 }