]>
Commit | Line | Data |
---|---|---|
1a4d82fc | 1 | // Copyright 2012-4 The Rust Project Developers. See the COPYRIGHT |
223e47cc LB |
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 | ||
c34b1796 | 15 | |
1a4d82fc JJ |
16 | #![feature(unboxed_closures)] |
17 | ||
223e47cc | 18 | trait iterable<A> { |
1a4d82fc | 19 | fn iterate<F>(&self, blk: F) -> bool where F: FnMut(&A) -> bool; |
223e47cc LB |
20 | } |
21 | ||
1a4d82fc JJ |
22 | impl<'a,A> iterable<A> for &'a [A] { |
23 | fn iterate<F>(&self, f: F) -> bool where F: FnMut(&A) -> bool { | |
24 | self.iter().all(f) | |
223e47cc LB |
25 | } |
26 | } | |
27 | ||
1a4d82fc JJ |
28 | impl<A> iterable<A> for Vec<A> { |
29 | fn iterate<F>(&self, f: F) -> bool where F: FnMut(&A) -> bool { | |
30 | self.iter().all(f) | |
223e47cc LB |
31 | } |
32 | } | |
33 | ||
c34b1796 | 34 | fn length<A, T: iterable<A>>(x: T) -> usize { |
223e47cc | 35 | let mut len = 0; |
1a4d82fc JJ |
36 | x.iterate(|_y| { |
37 | len += 1; | |
38 | true | |
39 | }); | |
223e47cc LB |
40 | return len; |
41 | } | |
42 | ||
43 | pub fn main() { | |
c34b1796 | 44 | let x: Vec<isize> = vec!(0,1,2,3); |
223e47cc | 45 | // Call a method |
62682a34 | 46 | x.iterate(|y| { assert_eq!(x[*y as usize], *y); true }); |
223e47cc | 47 | // Call a parameterized function |
970d7e83 | 48 | assert_eq!(length(x.clone()), x.len()); |
223e47cc LB |
49 | // Call a parameterized function, with type arguments that require |
50 | // a borrow | |
c34b1796 | 51 | assert_eq!(length::<isize, &[isize]>(&*x), x.len()); |
223e47cc LB |
52 | |
53 | // Now try it with a type that *needs* to be borrowed | |
54 | let z = [0,1,2,3]; | |
223e47cc | 55 | // Call a parameterized function |
c34b1796 | 56 | assert_eq!(length::<isize, &[isize]>(&z), z.len()); |
223e47cc | 57 | } |