rust 如何循环一定的(可变)次数?

rjee0c15  于 2023-02-08  发布在  其他
关注(0)|答案(3)|浏览(125)

这个问题看起来非常简单,但是我很难弄清楚怎么做,我有一个整数,我需要用一个for循环来循环整数次。
一开始,我试着-

fn main() {
    let number = 10; // Any value is ok
    for num in number {
        println!("success");
    }
}

这将打印错误

error[E0277]: `{integer}` is not an iterator
 --> src/main.rs:3:16
  |
3 |     for num in number{
  |                ^^^^^^ `{integer}` is not an iterator
  |
  = help: the trait `std::iter::Iterator` is not implemented for `{integer}`
  = note: if you want to iterate between `start` until a value `end`, use the exclusive range syntax `start..end` or the inclusive range syntax `start..=end`
  = note: required by `std::iter::IntoIterator::into_iter`

接下来,我试着-

fn main() {
    let number = 10; // Any value is ok
    for num in number.iter() {
        println!("success");
    }
}

编译器指出没有用于整数的iter方法

error[E0599]: no method named `iter` found for type `{integer}` in the current scope
 --> src/main.rs:3:23
  |
3 |     for num in number.iter() {
  |                       ^^^^

我该怎么做?

lnxxn5zx

lnxxn5zx1#

Rust for循环接受迭代器(实际上是任何可以是converted into an iterator的东西),唯一的整数不能转换成迭代器,但range可以。

fn main() {
    let number = 10; // Any value is ok
    for num in 0..number {
        println!("success");
    }
}

https://play.integer32.com/?version=stable&mode=debug&edition=2018&gist=029803cf8ac6efaa3113b2f32ae6ef0d

bxfogqkk

bxfogqkk2#

我想与大家分享Rust中这种基于闭包的、受Groovy启发的循环n次的方法。

pub trait Times {
    fn times(&self, f:fn(Self));
}

impl Times for u8 {
    fn times(&self, f:fn(u8)) {
        for x in 0..*self {
            f(x)
        }
    }
}

fn main() {
    const K: u8 =7;
    4.times( |v:u8| { println!("Inline Closure {v}.{K}"); } );
}

输出为:

Inline Closure 0.7
Inline Closure 1.7
Inline Closure 2.7
Inline Closure 3.7
ifmq2ha2

ifmq2ha23#

这是因为您是针对number中包含的num对编译器说的,其中number不是迭代器,也不实现iter,而不是针对range0..number中的num说的,num是迭代器。
文档将for循环描述为:

for loop_variable in iterator {
    code()
}

将代码更改为:

fn main() {
    let number = 10; 
    for num in 0..number { // change it to get range
        println!("success");
    }
}

您也可以将其更改为:

fn main() {
    let number = 10; 
    for num in 1..=number { // inclusive range
        println!("success");
    }
}

或发送至:

fn main() {
    let number = 10; 
    for _ in 0..number { // where _ is a "throw away" variable
        println!("success");
    }
}

另请参见for documentation

相关问题