How to make a reverse ordered for loop in Rust?

后端 未结 2 1632
迷失自我
迷失自我 2020-12-25 09:25

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

相关标签:
2条回答
  • 2020-12-25 10:00

    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.

    0 讨论(0)
  • 2020-12-25 10:14

    A forward loop is like this:

    for x in 0..100 {
        println!("{}", x);
    }
    

    And a reverse loop is done by calling Iterator::rev to reverse the order:

    for x in (0..100).rev() {
        println!("{}", x);
    }
    
    0 讨论(0)
提交回复
热议问题