我正在用 Rust 做一些简单的事情......只是触及一些你知道的基础。
所以我正在使用命令行参数,但我无法超越这个:
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
.
编辑:另外,如果我采用这种方法:
match arg1 {
"help" => { /* ... / },
_ => { / ... */ },
}
它抛出另一个错误:
error: mismatched types: expected collections::string::String but found &'static str (expected struct collections::string::String but found &-ptr)
最佳答案
您不能在 Rust 的 match
模式上使用变量。该代码被解释为将 arg1
上的任何值绑定(bind)为名为 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,
}
}
更新(感谢@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
。解决方案很简单:使用 String
上的 .as_slice()
方法从中取出切片,并能够将其与文字进行比较。
在代码中:
match arg1.as_slice() {
"help" => { /* ... */ },
_ => { /* ... */ },
}
关于match - 由于无法访问模式,Rust 匹配失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25006946/