簡體   English   中英

跳過、步進並返回正確索引的迭代器

[英]iterator that skips, steps by and returns correct index

我正在編寫一個程序,它需要一個迭代器,該迭代器從數組中的nth值開始,並逐步提供元素的正確索引 ( m n + xm )。 目前我的代碼:

fn main() {
    let mut test = [false; 10];

    for (index, val) in test.iter_mut().skip(3).step_by(2).enumerate() {
        *val = true;
        println!("{index} = true")
    }

    println!("{:?}", test)
}

// -> 
// 0 = true
// 1 = true
// 2 = true
// 3 = true
// [false, false, false, true, false, true, false, true, false, true]

給出正確的元素 ( val ) 但錯誤的索引 ( index )。 例如 output 的第一行應該是3 = true 你能告訴我如何獲得正確的index嗎?

謝謝,

TL;DR:在跳過之前枚舉

迭代器(實現Iterator的實例)上的操作是順序的。 它們懶惰地工作,通過應用另一種調用 inner 的next然后執行它自己的操作的類型。 我想說的是操作順序很重要 有了這些知識,您現在可以將枚舉放在此操作的開頭 pipe:

test.iter_mut()
    .enumerate()
    .skip(3)
    .step_by(2)
    .for_each(|(index, val)| {
        *val = true;
        println!("{index} = true");
    });

暫無
暫無

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

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