【Rust】迭代器(五)

环境

  • Time 2022-03-23
  • Rust 1.59.0

示例

find_map

fn main() {
    let vec = ["lol", "NaN", "2", "5"];
    let result: Option<i32> = vec.iter().find_map(|s| s.parse().ok());
    println!("{result:?}");
}

position

fn main() {
    let vec = vec![0, 1, 2, 3, 4];
    let result = vec.iter().position(|e| e > &2);
    println!("{result:?}");
}

rposition

fn main() {
    let vec = vec![0, 1, 2, 3, 4];
    let result = vec.iter().rposition(|e| e > &2);
    println!("{result:?}");
}

max

fn main() {
    let vec = vec![0, 1, 2, 3, 4];
    let result = vec.iter().max();
    println!("{result:?}");
}

min

fn main() {
    let vec = vec![0, 1, 2, 3, 4];
    let result = vec.iter().min();
    println!("{result:?}");
}

rev

fn main() {
    let vec = vec![0, 1, 2, 3, 4];
    vec.iter().rev().for_each(|e| println!("{e:?}"));
}

sum

fn main() {
    let vec = vec![0, 1, 2, 3, 4];
    let result: i32 = vec.iter().sum();
    println!("{result:?}");
}

product

fn main() {
    let vec = vec![0, 1, 2, 3, 4];
    let result: i32 = vec.iter().product();
    println!("{result:?}");
}

总结

了解了迭代器中相关的一些方法。

附录

posted @ 2022-05-28 13:38  jiangbo4444  阅读(50)  评论(0编辑  收藏  举报