]> git.lizzy.rs Git - rust.git/blob - src/test/run-pass/assignability-trait.rs
test: Automatically remove all `~[T]` from tests.
[rust.git] / src / test / run-pass / assignability-trait.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 // Tests that type assignability is used to search for instances when
12 // making method calls, but only if there aren't any matches without
13 // it.
14
15 trait iterable<A> {
16     fn iterate(&self, blk: |x: &A| -> bool) -> bool;
17 }
18
19 impl<'a,A> iterable<A> for &'a [A] {
20     fn iterate(&self, f: |x: &A| -> bool) -> bool {
21         self.iter().advance(f)
22     }
23 }
24
25 impl<A> iterable<A> for Vec<A> {
26     fn iterate(&self, f: |x: &A| -> bool) -> bool {
27         self.iter().advance(f)
28     }
29 }
30
31 fn length<A, T: iterable<A>>(x: T) -> uint {
32     let mut len = 0;
33     x.iterate(|_y| {
34         len += 1;
35         true
36     });
37     return len;
38 }
39
40 pub fn main() {
41     let x = vec!(0,1,2,3);
42     // Call a method
43     x.iterate(|y| { assert!(x[*y] == *y); true });
44     // Call a parameterized function
45     assert_eq!(length(x.clone()), x.len());
46     // Call a parameterized function, with type arguments that require
47     // a borrow
48     assert_eq!(length::<int, &[int]>(x), x.len());
49
50     // Now try it with a type that *needs* to be borrowed
51     let z = [0,1,2,3];
52     // Call a method
53     z.iterate(|y| { assert!(z[*y] == *y); true });
54     // Call a parameterized function
55     assert_eq!(length::<int, &[int]>(z), z.len());
56 }