我正在尝试实现一个函数,该函数读取命令行参数并将它们与硬编码的字符串文字进行比较。
当我使用一个if
语句进行比较时,它完美地工作:
fn main() {
let s = String::from("holla!");
if s == "holla!" {
println!("it worked!");
}
}
但是使用match
语句(我想这会更优雅):
fn main() {
let s = String::from("holla!");
match s {
"holla!" => println!("it worked!"),
_ => println!("nothing"),
}
}
编译器一直报错,说期望一个String
,但发现了一个&static str
:
error[E0308]: mismatched types
--> src/main.rs:5:9
|
5 | "holla!" => println!("it worked!"),
| ^^^^^^^^ expected struct `std::string::String`, found reference
|
= note: expected type `std::string::String`
found type `&'static str`
我看过如何在Rust中将字符串与字符串字面值匹配?,所以我知道如何修复它,但我想知道为什么在使用if
时比较可以工作,但不使用match
。
&str
是一个引用,而不是一个值。 - AJFif
比较而不能使用match
。 - robfuscatorif
语句委托给了PartialEq
的实现。match
没有这种特殊处理,因此需要一些帮助。这两个结构体本来就被编译成不同的形式,所以我不确定这对于编译器内部会如何工作。if
条件成为简单的分支,而match
似乎在编译时会变成类似于switch
的结构(根据LLVM IR)。 - Simon Whiteheadif else
是一个完全可以使用的良好结构。 - ljedrz