且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何做一个反向排序的Rust在循环?

更新时间:2023-11-04 07:55:22


编者按:铁锈1.0之前的铁锈。

您的代码不起作用,因为 uint 值-1的code>等于uint的最大值。 range_step迭代器在检测到溢出时立即停止。使用一个int修复了这个问题。

$ p $ st $ :: $ c $ std :: iter :: range_step(100i,0,-1)

您也可以使用 rev()来反转迭代器。 (0u,100).rev(){...}
>

$ p>

虽然请注意这将从99-> 0,而不是100-> 1。


Editor's note: This question was asked before Rust 1.0 was released and the .. "range" operator was introduced. The question's code no longer represents the current style, but some answers below uses code that will work in Rust 1.0 and onwards.

I was playing on the Rust by Example website and wanted to print out fizzbuzz in reverse. Here is what I tried:

fn main() {
    // `n` will take the values: 1, 2, ..., 100 in each iteration
    for n in std::iter::range_step(100u, 0, -1) {
        if n % 15 == 0 {
            println!("fizzbuzz");
        } else if n % 3 == 0 {
            println!("fizz");
        } else if n % 5 == 0 {
            println!("buzz");
        } else {
            println!("{}", n);
        }
    }
}

There were no compilation errors, but it did not print out anything. How do I iterate from 100 to 1?

Editor's note: This question refers to parts of Rust that predate Rust 1.0. Look at other answers for up to date code.

Your code doesn't work because a uint of value -1 is equal the maximum value of uint. The range_step iterator stops immediately upon detecting overflow. Using an int fixes this.

std::iter::range_step(100i, 0, -1)

You can also reverse an iterator with rev().

for n in range(0u, 100).rev() { ... }

Though note that this will be from 99->0, rather than 100->1.