gpt4 book ai didi

iterator - 如何遍历向后范围?

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

我正在尝试创建 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/

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