簡體   English   中英

實現 IntoIterator 的無約束類型參數

[英]Unconstrained type parameter implementing IntoIterator

我如何使用泛型類型參數實現 IntoIterator 而不會出現這種錯誤,我認為與此處的錯誤相同,但提出的解決方案在此上下文中無效,同時在Counter上執行一個名為iter的方法可以解決問題但它不會是慣用的

#[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)]
    );
}

游樂場鏈接

這可以在不需要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)
    }
}

操場

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM