]> git.lizzy.rs Git - rust.git/blob - src/test/run-pass/trait-generic.rs
a75a1b61c593c8edf463de528cc29446b9970ab0
[rust.git] / src / test / run-pass / trait-generic.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 // ignore-fast
12
13 trait to_str {
14     fn to_string(&self) -> ~str;
15 }
16 impl to_str for int {
17     fn to_string(&self) -> ~str { self.to_str() }
18 }
19 impl to_str for ~str {
20     fn to_string(&self) -> ~str { self.clone() }
21 }
22 impl to_str for () {
23     fn to_string(&self) -> ~str { ~"()" }
24 }
25
26 trait map<T> {
27     fn map<U>(&self, f: |&T| -> U) -> Vec<U> ;
28 }
29 impl<T> map<T> for Vec<T> {
30     fn map<U>(&self, f: |&T| -> U) -> Vec<U> {
31         let mut r = Vec::new();
32         // FIXME: #7355 generates bad code with VecIterator
33         for i in range(0u, self.len()) {
34             r.push(f(&self[i]));
35         }
36         r
37     }
38 }
39
40 fn foo<U, T: map<U>>(x: T) -> Vec<~str> {
41     x.map(|_e| ~"hi" )
42 }
43 fn bar<U:to_str,T:map<U>>(x: T) -> Vec<~str> {
44     x.map(|_e| _e.to_string() )
45 }
46
47 pub fn main() {
48     assert_eq!(foo(vec!(1)), vec!(~"hi"));
49     assert_eq!(bar::<int, Vec<int> >(vec!(4, 5)), vec!(~"4", ~"5"));
50     assert_eq!(bar::<~str, Vec<~str> >(vec!(~"x", ~"y")), vec!(~"x", ~"y"));
51     assert_eq!(bar::<(), vec!(())>(vec!(())), vec!(~"()"));
52 }