如何模式匹配选项<&Path>?

Pau*_*erg 2 pattern-matching rust

我的代码看起来像这样:

// my_path is of type "PathBuf"
match my_path.parent() {
    Some(Path::new(".")) => {
        // Do something.
    },
    _ => {
        // Do something else.
    }
}
Run Code Online (Sandbox Code Playgroud)

但我收到以下编译器错误:

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
Run Code Online (Sandbox Code Playgroud)

我读了Rust 书中的第 18 章,但我不知道如何使用PathPathBuf类型来修复我的特定场景。

如何通过检查特定值(如 )来进行模式匹配Option<&Path>(根据文档,这是方法返回的内容) ?parentPath::new("1")

Val*_*tin 5

如果你想使用一个match,那么你可以使用一个比赛守卫。简而言之,你不能使用的原因Some(Path::new("."))是因为Path::new(".")不是一个模式

match my_path.parent() {
    Some(p) if p == Path::new(".") => {
        // Do something.
    }
    _ => {
        // Do something else.
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,在这种特殊情况下,您也可以只使用 if 表达式,如下所示:

if my_path.parent() == Some(Path::new(".")) {
    // Do something.
} else {
    // Do something else.
}
Run Code Online (Sandbox Code Playgroud)