我正在做一些生锈的简单的东西...只是触摸你知道的一些地方.
所以我正在玩命令行参数,我不能通过这个:
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")
}
}
}
Run Code Online (Sandbox Code Playgroud)
我不能编译......错误是:
main.rs:17:4: 17:5 error: unreachable pattern
main.rs:17 _ => println!("no valid argument")
^
error: aborting due to previous error
Run Code Online (Sandbox Code Playgroud)
另外,我正在使用Rust 0.11.0-pre-nightly.
谢谢
编辑:另外,如果我采用这种方法:
match arg1 {
"help" => { /* ... / },
_ => { / ... */ },
}
Run Code Online (Sandbox Code Playgroud)
它引发了另一个错误:
error: mismatched types: expected collections::string::String but found &'static str (expected struct collections::string::String but found &-ptr)
Run Code Online (Sandbox Code Playgroud)
你不能在Rust的match模式上使用变量.代码被解释为绑定任何值arg1作为新的变量调用help_command,因此catch-all模式永远不会匹配.
您可以使用文字字符串来匹配arg1:
match arg1 {
"help" => { /* ... */ },
_ => { /* ... */ },
}
Run Code Online (Sandbox Code Playgroud)
或者使用警卫:
match arg1 {
command if command == help_command => { /* ... */ },
_ => { /* ... */ }
}
Run Code Online (Sandbox Code Playgroud)
如果您担心直接使用字符串的类型安全性和/或重复性,可以将命令解析为枚举:
enum Command {
HelpCommand,
DoStuffCommand
}
fn to_command(arg: &str) -> Option<Command> {
match arg {
"help" => Some(HelpCommand),
"do-stuff" => Some(DoStuffCommand),
_ => None,
}
}
Run Code Online (Sandbox Code Playgroud)
更新(感谢@ChrisMorgan):也可以使用静态变量:
static HELP: &'static str = "help";
match arg1 {
HELP => { /* ... */ },
_ => { /* ... */ },
}
Run Code Online (Sandbox Code Playgroud)
关于编辑问题中报告的错误:Rust有两种字符串:&str(字符串切片)和String(拥有的字符串).主要区别在于第二种是可生长的并且可以移动.请参阅链接以更好地理解区别.
您所遇到的错误是由于这样的事实,字符串("foo")是类型的&str,同时std::os::args()是Vec的String.解决方案很简单:使用上面的.as_slice()方法String从中取出切片,并将其与文字进行比较.
在代码中:
match arg1.as_slice() {
"help" => { /* ... */ },
_ => { /* ... */ },
}
Run Code Online (Sandbox Code Playgroud)