]> git.proxmox.com Git - rustc.git/blob - src/test/run-pass/assignability-trait.rs
New upstream version 1.14.0+dfsg1
[rustc.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 trait iterable<A> {
16 fn iterate<F>(&self, blk: F) -> bool where F: FnMut(&A) -> bool;
17 }
18
19 impl<'a,A> iterable<A> for &'a [A] {
20 fn iterate<F>(&self, f: F) -> bool where F: FnMut(&A) -> bool {
21 self.iter().all(f)
22 }
23 }
24
25 impl<A> iterable<A> for Vec<A> {
26 fn iterate<F>(&self, f: F) -> bool where F: FnMut(&A) -> bool {
27 self.iter().all(f)
28 }
29 }
30
31 fn length<A, T: iterable<A>>(x: T) -> usize {
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<isize> = vec![0,1,2,3];
42 // Call a method
43 x.iterate(|y| { assert_eq!(x[*y as usize], *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::<isize, &[isize]>(&*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 parameterized function
53 assert_eq!(length::<isize, &[isize]>(&z), z.len());
54 }