File: impl-trait-to-trait-method-pass.rs

package info (click to toggle)
rustc 1.87.0%2Bdfsg1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 925,564 kB
  • sloc: xml: 158,127; python: 36,039; javascript: 19,761; sh: 19,737; cpp: 18,981; ansic: 13,133; asm: 4,376; makefile: 710; perl: 29; lisp: 28; ruby: 19; sql: 11
file content (77 lines) | stat: -rw-r--r-- 1,751 bytes parent folder | download | duplicates (17)
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
70
71
72
73
74
75
76
77
//@ run-pass

#![feature(fn_delegation)]
#![allow(incomplete_features)]

use std::iter::{Iterator, Map};

pub mod same_trait {
    use super::*;

    pub struct MapOuter<I, F> {
        pub inner: Map<I, F>
    }

    impl<B, I: Iterator, F> Iterator for MapOuter<I, F>
    where
        F: FnMut(I::Item) -> B,
    {
        type Item = <Map<I, F> as Iterator>::Item;

        reuse Iterator::{next, fold} { self.inner }
    }
}
use same_trait::MapOuter;

mod another_trait {
    use super::*;

    trait ZipImpl<A, B> {
        type Item;

        fn next(&mut self) -> Option<Self::Item>;
    }

    pub struct Zip<A, B> {
        pub a: A,
        pub b: B,
    }

    impl<A: Iterator, B: Iterator> ZipImpl<A, B> for Zip<A, B> {
        type Item = (A::Item, B::Item);

        fn next(&mut self) -> Option<(A::Item, B::Item)> {
            let x = self.a.next()?;
            let y = self.b.next()?;
            Some((x, y))
        }
    }

    impl<A: Iterator, B: Iterator> Iterator for Zip<A, B> {
        type Item = (A::Item, B::Item);

        // Parameters are inherited from `Iterator::next`, not from `ZipImpl::next`.
        // Otherwise, there would be a compilation error due to an unconstrained parameter.
        reuse ZipImpl::next;
    }
}
use another_trait::Zip;

fn main() {
    {
        let x = vec![1, 2, 3];
        let iter = x.iter().map(|val| val * 2);
        let outer_iter = MapOuter { inner: iter };
        let val = outer_iter.fold(0, |acc, x| acc + x);
        assert_eq!(val, 12);
    }

    {
        let x = vec![1, 2];
        let y = vec![4, 5];

        let mut zip = Zip { a: x.iter(), b: y.iter() };
        assert_eq!(zip.next(), Some((&1, &4)));
        assert_eq!(zip.next(), Some((&2, &5)));
    }
}