首页 > 解决方案 > 如何在 match 语句分支中声明变量?

问题描述

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

你的任务是为臭名昭著的深奥语言 HQ9+ 实现一个简单的解释器,它适用于单个字符输入:

  • 如果输入为“H”,则返回“Hello World!”
  • 如果输入是'Q',则返回输入
  • 如果输入是“9”,则返回 99 瓶啤酒的完整歌词。

由于某种原因,我无法让它工作。我不知道我在这里错过了什么。如何在 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,
    }
}

标签: rust

解决方案


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

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,
    }
}

修复此问题会暴露其他错误。


推荐阅读