gpt4 book ai didi

rust - 如何在match语句分支中声明变量?

转载 作者:行者123 更新时间:2023-12-03 11:41:26 26 4
gpt4 key购买 nike

我正在尝试解决一个任务
https://www.codewars.com/kata/591588d49f4056e13f000001/train/rust

Your task is to implement an simple interpreter for the notorious esoteric language HQ9+ that will work for a single character input:

  • If the input is 'H', return 'Hello World!'
  • If the input is 'Q', return the input
  • If the input is '9', return the full lyrics of 99 Bottles of Beer.

由于某种原因,我无法使其正常运行。我不知道我在这里错过了什么。如何在match语句分支中声明变量?
fn hq9(code: &str) -> Option<String> {
match code{
"H" => Some("Hello World!".to_string()),
"Q" => Some("Q".to_string()),
"9" => let s = String::new();
(0..=99).rev().for_each(|x|
match x {
x @ 3..=99 => s.push_str("{} bottles of beer on the wall, {} bottles of beer.\nTake one down and pass it around, {} bottles of beer on the wall.\n",x,x,x-1),
2 => s.push_str("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"),
1 => s.push_str("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"),
0 => s.push_str("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"),
_ => panic!(),
})
Some(s),
_ => None,
}
}

最佳答案

匹配臂使用语法PATTERN => EXPRESSION,如果表达式需要多个语句,请使用block {}:

fn hq9(code: &str) -> Option<String> {
match code {
"H" => Some("Hello World!".to_string()),
"Q" => Some("Q".to_string()),
"9" => { // <----------------- start block
let s = String::new();
(0..=99).rev().for_each(|x|
match x {
x @ 3..=99 => s.push_str("{} bottles of beer on the wall, {} bottles of beer.\nTake one down and pass it around, {} bottles of beer on the wall.\n",x,x,x-1),
2 => s.push_str("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"),
1 => s.push_str("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"),
0 => s.push_str("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"),
_ => panic!(),
});
Some(s)
} // <----------------- end block
_ => None,
}
}
解决此问题会暴露其他错误。

关于rust - 如何在match语句分支中声明变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66608888/

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