首页 > 解决方案 > 如何对 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 章,但我不知道如何使用PathandPathBuf类型修复我的特定场景。

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

标签: rustpattern-matching

解决方案


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

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.
}

推荐阅读