]> git.lizzy.rs Git - rust.git/blob - src/test/run-pass/assignability-trait.rs
57c50511604ca3f095418cac0f56ca53e264191a
[rust.git] / src / test / run-pass / assignability-trait.rs
1 // Copyright 2012-4 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 #![feature(unboxed_closures)]
16
17 trait iterable<A> {
18     fn iterate<F>(&self, blk: F) -> bool where F: FnMut(&A) -> bool;
19 }
20
21 impl<'a,A> iterable<A> for &'a [A] {
22     fn iterate<F>(&self, f: F) -> bool where F: FnMut(&A) -> bool {
23         self.iter().all(f)
24     }
25 }
26
27 impl<A> iterable<A> for Vec<A> {
28     fn iterate<F>(&self, f: F) -> bool where F: FnMut(&A) -> bool {
29         self.iter().all(f)
30     }
31 }
32
33 fn length<A, T: iterable<A>>(x: T) -> uint {
34     let mut len = 0;
35     x.iterate(|_y| {
36         len += 1;
37         true
38     });
39     return len;
40 }
41
42 pub fn main() {
43     let x: Vec<int> = vec!(0,1,2,3);
44     // Call a method
45     x.iterate(|y| { assert!(x[*y as uint] == *y); true });
46     // Call a parameterized function
47     assert_eq!(length(x.clone()), x.len());
48     // Call a parameterized function, with type arguments that require
49     // a borrow
50     assert_eq!(length::<int, &[int]>(&*x), x.len());
51
52     // Now try it with a type that *needs* to be borrowed
53     let z = [0,1,2,3];
54     // Call a parameterized function
55     assert_eq!(length::<int, &[int]>(&z), z.len());
56 }