1 // run-pass
2 
3 #![feature(generic_associated_types)]
4 
5 use std::fmt::Display;
6 
7 trait StreamingIterator {
8     type Item<'a> where Self: 'a;
9     // Applying the lifetime parameter `'a` to `Self::Item` inside the trait.
next<'a>(&'a mut self) -> Option<Self::Item<'a>>10     fn next<'a>(&'a mut self) -> Option<Self::Item<'a>>;
11 }
12 
13 struct Foo<T: StreamingIterator + 'static> {
14     // Applying a concrete lifetime to the constructor outside the trait.
15     bar: <T as StreamingIterator>::Item<'static>,
16 }
17 
18 // Users can bound parameters by the type constructed by that trait's associated type constructor
19 // of a trait using HRTB. Both type equality bounds and trait bounds of this kind are valid:
20 //FIXME(#44265): This next line should parse and be valid
21 //fn foo<T: for<'a> StreamingIterator<Item<'a>=&'a [i32]>>(_iter: T) { /* ... */ }
_foo<T>(_iter: T) where T: StreamingIterator, for<'a> T::Item<'a>: Display22 fn _foo<T>(_iter: T) where T: StreamingIterator, for<'a> T::Item<'a>: Display { /* ... */ }
23 
24 // Full example of enumerate iterator
25 
26 #[must_use = "iterators are lazy and do nothing unless consumed"]
27 struct StreamEnumerate<I> {
28     iter: I,
29     count: usize,
30 }
31 
32 impl<I: StreamingIterator> StreamingIterator for StreamEnumerate<I> {
33     type Item<'a> where Self: 'a = (usize, I::Item<'a>);
next<'a>(&'a mut self) -> Option<Self::Item<'a>>34     fn next<'a>(&'a mut self) -> Option<Self::Item<'a>> {
35         match self.iter.next() {
36             None => None,
37             Some(val) => {
38                 let r = Some((self.count, val));
39                 self.count += 1;
40                 r
41             }
42         }
43     }
44 }
45 
46 impl<I: Iterator> StreamingIterator for I {
47     type Item<'a> where Self: 'a = <I as Iterator>::Item;
next(&mut self) -> Option<<I as StreamingIterator>::Item<'_>>48     fn next(&mut self) -> Option<<I as StreamingIterator>::Item<'_>> {
49         Iterator::next(self)
50     }
51 }
52 
53 impl<I> StreamEnumerate<I> {
new(iter: I) -> Self54     pub fn new(iter: I) -> Self {
55         StreamEnumerate {
56             count: 0,
57             iter,
58         }
59     }
60 }
61 
test_stream_enumerate()62 fn test_stream_enumerate() {
63     let v = vec!["a", "b", "c"];
64     let mut se = StreamEnumerate::new(v.iter());
65     while let Some(item) = se.next() {
66         assert_eq!(v[item.0], *item.1);
67     }
68     let x = Foo::<std::slice::Iter<'static, u32>> {
69         bar: &0u32,
70     };
71     assert_eq!(*x.bar, 0u32);
72 }
73 
main()74 fn main() {
75     test_stream_enumerate();
76 }
77