匹配失败,因为模式[重复项]不可到达

问题描述 投票:2回答:1

我正在做一些生锈的简单事情……只是碰到一些你知道的地面。

所以我当时在玩命令行参数,所以不能超越:

use std::os::args;

fn main(){

    let arg1 = args().get(1).to_str();

    let help_command = "help";

    if args().len() == 1 {
            println!("No arguments.");
    }

    else if args().len() == 2 {

            match arg1 {
                    help_command => println!("Do ..."),
                    _    => println!("no valid argument")
            }

    }

}

我无法编译...错误是:

main.rs:17:4: 17:5 error: unreachable pattern
main.rs:17                      _    => println!("no valid argument")
                                ^
error: aborting due to previous error

另外,我正在使用Rust 0.11.0-pre-nightly

EDIT:另外,如果我采用这种方法:

match arg1 { 
    "help" => { /* ... / }, 
    _ => { / ... */ }, 
}

引发另一个错误:

error: mismatched types: expected collections::string::String but found &'static str (expected struct collections::string::String but found &-ptr) 
match rust
1个回答
5
投票

您不能在Rust的match模式上使用变量。该代码被解释为将arg1上的任何值绑定为一个称为help_command的新变量,因此,包罗万象的模式从不匹配。

您可以使用文字字符串来匹配arg1

match arg1 {
    "help" => { /* ... */ },
    _      => { /* ... */ },
}

或使用警卫:

match arg1 {
    command if command == help_command => { /* ... */ },
    _ => { /* ... */ }
}

如果您担心直接使用字符串的类型安全性和/或重复性,可以将命令解析为一个枚举:

enum Command {
    HelpCommand,
    DoStuffCommand
}

fn to_command(arg: &str) -> Option<Command> {
    match arg {
        "help"     => Some(HelpCommand),
        "do-stuff" => Some(DoStuffCommand),
        _          => None,
    }
}

Working example

Update(感谢@ChrisMorgan):也可以使用静态变量:

static HELP: &'static str = "help";

match arg1 {
    HELP => { /* ... */ },
    _ => { /* ... */ },
}

关于问题编辑中报告的错误:Rust具有两种字符串:&str (string slice)String (owned string)。主要区别在于第二种是可生长的并且可以移动。请参阅链接以更好地理解区别。

您遇到的错误是由于以下事实:字符串文字("foo")的类型为&str,而std::os::args() is a Vec of String。解决方案很简单:使用std::os::args()上的Vec方法从中取出切片,并能够将其与文字进行比较。

使用代码:

String
© www.soinside.com 2019 - 2024. All rights reserved.