[英]How to to pattern match an Option<&Path>?
我的代碼看起來像這樣:
// my_path is of type "PathBuf"
match my_path.parent() {
Some(Path::new(".")) => {
// Do something.
},
_ => {
// Do something else.
}
}
但是我收到以下編譯器錯誤:
expected tuple struct or tuple variant, found associated function `Path::new`
for more information, visit https://doc.rust-lang.org/book/ch18-00-patterns.html
我閱讀了 Rust 書中的第 18 章,但我無法弄清楚如何使用Path
和PathBuf
類型修復我的特定場景。
我如何通過檢查Path::new("1")
類的特定值來模式匹配Option<&Path>
(根據文檔,這是parent
方法返回的內容)?
如果你想使用match
,那么你可以使用火柴后衛。 簡而言之,您不能使用Some(Path::new("."))
的原因是因為Path::new(".")
不是pattern 。
match my_path.parent() {
Some(p) if p == Path::new(".") => {
// Do something.
}
_ => {
// Do something else.
}
}
但是,在那種特殊情況下,您也可以只使用 if 表達式,如下所示:
if my_path.parent() == Some(Path::new(".")) {
// Do something.
} else {
// Do something else.
}
兩個選項,將path
轉換為str
或使用匹配守衛。 下面兩個例子:
use std::path::{Path, PathBuf};
fn map_to_str(my_path: PathBuf) {
match my_path.parent().map(|p| p.to_str().unwrap()) {
Some(".") => {
// Do something
},
_ => {
// Do something else
}
}
}
fn match_guard(my_path: PathBuf) {
match my_path.parent() {
Some(path) if path == Path::new(".") => {
// Do something
},
_ => {
// Do something else
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.