rust 迭代器

https://blog.csdn.net/guiqulaxi920/article/details/78823541

 

fn main() {

    // Basic Range (exclusive on the right)
    for i in 1..11 {
        print!("{} ", i);
    }
    println!("");

    // Inclusive range
    for i in 1..=10 {
        print!("{} ", i);
    }
    println!("");

    // use of discard "_" pattern
    let mut n: i32 = 0;
    for _ in 0..10 {
        n += 1;
    }
    println!("num = {}", n);

    // count()
    println!("num = {}", (0..10).count());

    // Range with step using a filter
    for i in (0..21).filter(|x| (x % 2 == 0)) {
      print!("{} ", i);
    }
    println!("");


    // Reverse range
    for i in (0..11).rev() {
        print!("{} ", i);
    }
    println!("");

    // map()
    for i in (1..11).map(|x| x * x) {
        print!("{} ", i);
    }
    println!("");

    // fold()
    let result = (1..=5).fold(0, |acc, x| acc + x * x);
    println!("result = {}", result);
}

 

[root@bogon iter]# cargo run
    Finished dev [unoptimized + debuginfo] target(s) in 0.01s
     Running `target/debug/hello_world`
1 2 3 4 5 6 7 8 9 10 
1 2 3 4 5 6 7 8 9 10 
num = 10
num = 10
0 2 4 6 8 10 12 14 16 18 20 
10 9 8 7 6 5 4 3 2 1 0 
1 4 9 16 25 36 49 64 81 100 
result = 55

 

#![feature(inclusive_range_syntax)]

let mut acc = 0;

for x in 1...5 {
  acc += x * x;
}

let result = acc;
println!("result = {}", result);

// output: result = 55

 

posted on 2020-12-28 17:39  tycoon3  阅读(132)  评论(0编辑  收藏  举报

导航