gpt4 book ai didi

for-loop - 如何循环特定(可变)次数?

转载 作者:行者123 更新时间:2023-11-29 08:08:26 24 4
gpt4 key购买 nike

这个问题可能看起来非常基础,但我很难弄清楚如何做。我有一个整数,我需要使用 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");
}
}

编译器说没有整数的方法迭代器

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() {
| ^^^^

我应该怎么做?

最佳答案

这是因为您要告诉编译器 number 中包含的 num,其中 number 不是迭代器,也没有实现 iter ,而不是 range 0..number 中的 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

关于for-loop - 如何循环特定(可变)次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55965160/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com