How can I iterate over a backwards range?

前端 未结 1 355
有刺的猬
有刺的猬 2021-01-28 22:41

I\'m attempting to create pub fn sing(start: i32, end: i32) -> String that returns a concatenated string of the results of calling pub fn verse(num: i32) -

相关标签:
1条回答
  • 2021-01-28 22:58

    Your problem has nothing to do with string concatenation. It has to do with the fact that 8..6 is an empty iterator, because a range only iterates forwards. Because 8 >= 6, the iterator yields None on the first call to next.

    fn main() {
        for i in 8..6 {
            println!("{}", i); // never reached
        }
    }
    

    This can be fixed by swapping start and end and calling rev() to iterate backwards.

    fn main() {
        for i in (6..8).rev() {
            println!("{}", i);
        }
    }
    

    However, there's still another problem. In a range start..end, start is inclusive but end is exclusive. For example, the code above prints 7 and 6; 8 is not printed. See How do I include the end value in a range?

    Putting it all together, sing should look like:

    pub fn sing(start: i32, end: i32) -> String {
        (end..=start)
            .rev()
            .fold(String::new(), |ans, x| ans + &verse(x))
    }
    

    Note: Your test still fails because it expects two newlines between each verse, but your code only generates one. I'll leave this up to you to fix.

    0 讨论(0)
提交回复
热议问题