]> git.lizzy.rs Git - rust.git/blob - src/test/run-pass/static-impl.rs
b66999c8e67229083cb4a52328a701f7b317ea9b
[rust.git] / src / test / run-pass / static-impl.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
13 pub trait plus {
14     fn plus(&self) -> int;
15 }
16
17 mod a {
18     use plus;
19     impl plus for uint { fn plus(&self) -> int { *self as int + 20 } }
20 }
21
22 mod b {
23     use plus;
24     impl plus for String { fn plus(&self) -> int { 200 } }
25 }
26
27 trait uint_utils {
28     fn str(&self) -> String;
29     fn multi<F>(&self, f: F) where F: FnMut(uint);
30 }
31
32 impl uint_utils for uint {
33     fn str(&self) -> String {
34         self.to_string()
35     }
36     fn multi<F>(&self, mut f: F) where F: FnMut(uint) {
37         let mut c = 0_usize;
38         while c < *self { f(c); c += 1_usize; }
39     }
40 }
41
42 trait vec_utils<T> {
43     fn length_(&self, ) -> uint;
44     fn iter_<F>(&self, f: F) where F: FnMut(&T);
45     fn map_<U, F>(&self, f: F) -> Vec<U> where F: FnMut(&T) -> U;
46 }
47
48 impl<T> vec_utils<T> for Vec<T> {
49     fn length_(&self) -> uint { self.len() }
50     fn iter_<F>(&self, mut f: F) where F: FnMut(&T) { for x in self { f(x); } }
51     fn map_<U, F>(&self, mut f: F) -> Vec<U> where F: FnMut(&T) -> U {
52         let mut r = Vec::new();
53         for elt in self {
54             r.push(f(elt));
55         }
56         r
57     }
58 }
59
60 pub fn main() {
61     assert_eq!(10_usize.plus(), 30);
62     assert_eq!(("hi".to_string()).plus(), 200);
63
64     assert_eq!((vec!(1)).length_().str(), "1".to_string());
65     let vect = vec!(3, 4).map_(|a| *a + 4);
66     assert_eq!(vect[0], 7);
67     let vect = (vec!(3, 4)).map_::<uint, _>(|a| *a as uint + 4_usize);
68     assert_eq!(vect[0], 7_usize);
69     let mut x = 0_usize;
70     10_usize.multi(|_n| x += 2_usize );
71     assert_eq!(x, 20_usize);
72 }