iterator - 如何遍历向后范围?

标签 iterator rust match

我正在尝试创建 pub fn sing(start: i32, end: i32) -> String 返回调用 pub fn verse(num: i32) -> Stringstartend 之间的每个数字上重复。

我用谷歌搜索了答案,似乎是 Rust String concatenation回答我的问题,如果我什至在 playground 中编写代码它有效,但是:

我的代码:

pub fn verse(num: i32) -> String {
    match num {
        0 => "No more bottles of beer on the wall, no more bottles of beer.\nGo to the store and buy some more, 99 bottles of beer on the wall.\n".to_string(),
        1 => "1 bottle of beer on the wall, 1 bottle of beer.\nTake it down and pass it around, no more bottles of beer on the wall.\n".to_string(),
        2 => "2 bottles of beer on the wall, 2 bottles of beer.\nTake one down and pass it around, 1 bottle of beer on the wall.\n".to_string(),
        num => format!("{0} bottles of beer on the wall, {0} bottles of beer.\nTake one down and pass it around, {1} bottles of beer on the wall.\n",num,(num-1)),
    }
}

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

问题是

#[test]
fn test_song_8_6() {
    assert_eq!(beer::sing(8, 6), "8 bottles of beer on the wall, 8 bottles of beer.\nTake one down and pass it around, 7 bottles of beer on the wall.\n\n7 bottles of beer on the wall, 7 bottles of beer.\nTake one down and pass it around, 6 bottles of beer on the wall.\n\n6 bottles of beer on the wall, 6 bottles of beer.\nTake one down and pass it around, 5 bottles of beer on the wall.\n");
}

失败,beer::sing(8,6) 返回 ""

最佳答案

您的问题与字符串连接无关。它与 8..6 是一个空迭代器这一事实有关,因为范围只能向前迭代。因为 8 >= 6,迭代器在第一次调用 next 时产生 None

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

这可以通过交换 startend 并调用 rev() 向后迭代来解决。

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

但是,还有一个问题。在 start..end 范围内,start 包含在内,但 end 不包含在内。例如,上面的代码打印出 768 未打印。参见 How do I include the end value in a range?

将它们放在一起,sing 应该是这样的:

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

注意:您的测试仍然失败,因为它期望每节之间有两个换行符,但您的代码只生成一个。我会把这个留给你来解决。 🙂

关于iterator - 如何遍历向后范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53842907/

相关文章:

ruby-on-rails - rails : An elegant way to display a message when there are no elements in database

rust - 如何在 CentOS 的 conda 上包含所需的 cargo 编译器?

concurrency - Rust 文档中的进餐哲学家不会同时进餐

match - Any.match 是做什么的?

javascript - 在 JavaScript 中查找与字符串不匹配的行

java - Xpath 在 java 中使用 NodeIterator

javascript - 使用 Javascript RegExp 用迭代数字替换每个匹配项

python - 有没有办法检查两个对象在 python 中的每个变量中是否包含相同的值?

c++ - 如何从两个字符串列表中删除公共(public)值

rust - 错误[E0502] : cannot borrow `vector` as immutable because it is also borrowed as mutable