如何模式匹配 Option<&Path>?
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
我阅读了 chapter 18 from the Rust book,但我无法弄清楚如何使用 Path
和 PathBuf
类型解决我的特定情况。
如何通过检查 [=16] 等特定值来模式匹配 Option<&Path>
(根据 docs 这就是 parent
方法 returns) =]?
如果你想使用match
,那么你可以使用match guard. In short, the reason you can't use Some(Path::new("."))
is because Path::new(".")
is not a 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
}
}
}
我的代码看起来像这样:
// 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
我阅读了 chapter 18 from the Rust book,但我无法弄清楚如何使用 Path
和 PathBuf
类型解决我的特定情况。
如何通过检查 [=16] 等特定值来模式匹配 Option<&Path>
(根据 docs 这就是 parent
方法 returns) =]?
如果你想使用match
,那么你可以使用match guard. In short, the reason you can't use Some(Path::new("."))
is because Path::new(".")
is not a 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
}
}
}