如何使用泛型型別引數實作 IntoIterator 而不會出現此類錯誤,我認為與此處的錯誤相同,但提出的解決方案在此背景關系中無效,也執行呼叫的方法iter可以Counter解決問題,但它不會是慣用語
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Id(u32);
struct Counter {
top: u32
}
struct Iter<R: Iterator<Item = Id>>(R);
impl<R> Iterator for Iter<R>
where
R: Iterator<Item = Id>
{
type Item = Id;
fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
}
// Unconstrained type parameter `I`
impl<I> IntoIterator for Counter
where
I: Iterator<Item = Id>
{
type Item = Id;
type IntoIter = I;
fn into_iter(self) -> Self::IntoIter {
Iter(0..self.top)
}
}
這是我期望從實作中得到的行為。
fn main() {
let mut counter = Counter { top: 3 };
assert_eq!(
counter.into_iter().collect::<Vec<Id>>(),
vec![Id(0), Id(1), Id(2)]
);
}
鏈接到游樂場
uj5u.com熱心網友回復:
這可以在不需要I型別引數的情況下解決:
struct Iter<R: Iterator<Item = u32>>(R);
impl<R> Iterator for Iter<R>
where
R: Iterator<Item = u32>,
{
type Item = Id;
fn next(&mut self) -> Option<Self::Item> {
self.0.next().map(Id)
}
}
impl IntoIterator for Counter {
type Item = Id;
type IntoIter = Iter<std::ops::Range<u32>>;
fn into_iter(self) -> Self::IntoIter {
Iter(0..self.top)
}
}
操場
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/465682.html
