码迷,mamicode.com
首页 > 其他好文 > 详细

rust 迭代器

时间:2021-01-01 12:55:18      阅读:0      评论:0      收藏: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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!