blob: 15f429afb0274c46a37e8fe6f760c3f1cc01f673 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
|
#![feature(associated_type_defaults)]
// A Collection trait and collection families. Based on
// https://smallcultfollowing.com/babysteps/blog/2016/11/03/
// associated-type-constructors-part-2-family-traits/
// run-pass
trait Collection<T> {
type Iter<'iter>: Iterator<Item=&'iter T> where T: 'iter, Self: 'iter;
type Family: CollectionFamily;
// Test associated type defaults with parameters
type Sibling<U>: Collection<U> =
<<Self as Collection<T>>::Family as CollectionFamily>::Member<U>;
fn empty() -> Self;
fn add(&mut self, value: T);
fn iterate<'iter>(&'iter self) -> Self::Iter<'iter>;
}
trait CollectionFamily {
type Member<T>: Collection<T, Family = Self>;
}
struct VecFamily;
impl CollectionFamily for VecFamily {
type Member<T> = Vec<T>;
}
impl<T> Collection<T> for Vec<T> {
type Iter<'iter> = std::slice::Iter<'iter, T> where T: 'iter;
type Family = VecFamily;
fn empty() -> Self {
Vec::new()
}
fn add(&mut self, value: T) {
self.push(value)
}
fn iterate<'iter>(&'iter self) -> Self::Iter<'iter> {
self.iter()
}
}
fn floatify<C>(ints: &C) -> <<C as Collection<i32>>::Family as CollectionFamily>::Member<f32>
where
C: Collection<i32>,
{
let mut res = <C::Family as CollectionFamily>::Member::<f32>::empty();
for &v in ints.iterate() {
res.add(v as f32);
}
res
}
fn use_floatify() {
let a = vec![1, 2, 3];
let b = floatify(&a);
assert_eq!(Some(&1.0), b.iterate().next());
}
fn main() {
use_floatify();
}
|