rust 迭代器

技术文章 7个月前 完美者
1,196 0

标签:style   pattern   ==   result   log   debug   using   迭代器   csdn   

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

 

rust 迭代器

标签:style   pattern   ==   result   log   debug   using   迭代器   csdn   

原文地址:https://www.cnblogs.com/dream397/p/14202732.html

版权声明:完美者 发表于 2021-01-01 12:55:18。
转载请注明:rust 迭代器 | 完美导航

暂无评论

暂无评论...