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