2018-08-30 14:18:55 +02:00
|
|
|
// run-pass
|
2018-08-31 15:02:01 +02:00
|
|
|
#![allow(non_camel_case_types)]
|
|
|
|
|
2012-07-06 15:50:50 -07:00
|
|
|
// Tests that type assignability is used to search for instances when
|
|
|
|
// making method calls, but only if there aren't any matches without
|
|
|
|
// it.
|
|
|
|
|
2012-07-31 10:27:51 -07:00
|
|
|
trait iterable<A> {
|
2014-12-03 20:42:22 -05:00
|
|
|
fn iterate<F>(&self, blk: F) -> bool where F: FnMut(&A) -> bool;
|
2012-07-06 15:50:50 -07:00
|
|
|
}
|
|
|
|
|
2013-12-09 23:16:18 -08:00
|
|
|
impl<'a,A> iterable<A> for &'a [A] {
|
2014-12-03 20:42:22 -05:00
|
|
|
fn iterate<F>(&self, f: F) -> bool where F: FnMut(&A) -> bool {
|
2014-07-07 15:22:23 -07:00
|
|
|
self.iter().all(f)
|
2012-07-06 15:50:50 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-03-05 14:02:44 -08:00
|
|
|
impl<A> iterable<A> for Vec<A> {
|
2014-12-03 20:42:22 -05:00
|
|
|
fn iterate<F>(&self, f: F) -> bool where F: FnMut(&A) -> bool {
|
2014-07-07 15:22:23 -07:00
|
|
|
self.iter().all(f)
|
2012-07-06 15:50:50 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-03-25 17:06:52 -07:00
|
|
|
fn length<A, T: iterable<A>>(x: T) -> usize {
|
2012-07-06 15:50:50 -07:00
|
|
|
let mut len = 0;
|
2013-11-21 17:23:21 -08:00
|
|
|
x.iterate(|_y| {
|
|
|
|
len += 1;
|
|
|
|
true
|
|
|
|
});
|
2012-08-01 17:30:05 -07:00
|
|
|
return len;
|
2012-07-06 15:50:50 -07:00
|
|
|
}
|
|
|
|
|
2013-02-01 19:43:17 -08:00
|
|
|
pub fn main() {
|
2016-10-29 22:54:04 +01:00
|
|
|
let x: Vec<isize> = vec![0,1,2,3];
|
2012-07-06 15:50:50 -07:00
|
|
|
// Call a method
|
2015-06-07 21:00:38 +03:00
|
|
|
x.iterate(|y| { assert_eq!(x[*y as usize], *y); true });
|
2012-07-06 15:50:50 -07:00
|
|
|
// Call a parameterized function
|
2013-05-18 22:02:45 -04:00
|
|
|
assert_eq!(length(x.clone()), x.len());
|
2012-07-06 15:50:50 -07:00
|
|
|
// Call a parameterized function, with type arguments that require
|
|
|
|
// a borrow
|
2015-03-25 17:06:52 -07:00
|
|
|
assert_eq!(length::<isize, &[isize]>(&*x), x.len());
|
2012-07-06 15:50:50 -07:00
|
|
|
|
|
|
|
// Now try it with a type that *needs* to be borrowed
|
2012-10-10 00:28:04 -04:00
|
|
|
let z = [0,1,2,3];
|
2012-07-06 15:50:50 -07:00
|
|
|
// Call a parameterized function
|
2015-03-25 17:06:52 -07:00
|
|
|
assert_eq!(length::<isize, &[isize]>(&z), z.len());
|
2012-07-06 15:50:50 -07:00
|
|
|
}
|