[英]Why can I compare a String to a &str using if, but not when using match?
我正在嘗試實現一個函數,該函數讀取命令行參數並將它們與硬編碼的字符串文字進行比較。
當我與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
時比較有效。
我想知道為什么在
if
但不使用match
時比較有效。
這與if
和 more 無關,因為您在條件中使用了==
。 if
語句中的條件是bool
類型的任何表達式; 你只是碰巧選擇在那里使用==
。
==
運算符實際上是一個與PartialEq
trait相關的函數。 可以為任何類型對實現此特征。 而且,為了方便起見, String
有PartialEq<str>
和PartialEq<&str>
等的實現——反之亦然。
另一方面, match
表達式使用模式匹配進行比較,而不是==
。 一個&'static str
文字,比如"holla!"
, 是一個有效的模式,但它永遠無法匹配String
,后者是一種完全不同的類型。
模式匹配讓您可以簡潔地比較復雜結構的各個部分,即使整個結構不相等,也可以將變量綁定到匹配的部分。 雖然String
並沒有真正從中受益,但它對於其他類型非常強大,並且具有與==
完全不同的目的。
請注意,您可以使用if
by 模式匹配,而不是使用if let
構造。 您的示例如下所示:
if let "holla!" = &*s {
println!("it worked!");
}
相反,在match
使用==
一種方法是這樣的:
match s {
_ if s == "holla!" => println!("it worked!"),
_ => println!("nothing"),
}
或者,正如@ljedrz 建議的那樣:
match s == "holla!" {
true => println!("it worked!"),
_ => println!("nothing")
}
正如@peter-hall 所說,存在類型不匹配,因為match
表達式使用模式匹配,這與與PartialEq
特征關聯的==
不同。
有第二種方法可以解決此問題,將String
轉換為&str
(字符串切片):
match &s[..] {
"holla!" => println!("it worked!"),
"Hallo!" => println!("with easy to read matches !"),
_ => println!("nothing"),
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.