如何模式匹配 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,但我不知道如何使用 PathPathBuf 类型修复我的特定场景。

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

解决方法

如果您想使用 match,那么您可以使用 match guard。简而言之,您不能使用 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
        }
    }
}

playground