简体   繁体   English

如何模式匹配 Option<&Path>?

[英]How to to pattern match an Option<&Path>?

My code looks something like this:我的代码看起来像这样:

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

But I'm getting the following compiler error:但是我收到以下编译器错误:

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

I read chapter 18 from the Rust book but I couldn't figure out how to fix my specific scenario with the Path and PathBuf types.我阅读了 Rust 书中的第 18 章,但我无法弄清楚如何使用PathPathBuf类型修复我的特定场景。

How can I pattern match an Option<&Path> (according to the docs this is what the parent methods returns) by checking for specific values like Path::new("1") ?我如何通过检查Path::new("1")类的特定值来模式匹配Option<&Path> (根据文档,这是parent方法返回的内容)?

If you want to use a match , then you can use a match guard .如果你想使用match ,那么你可以使用火柴后卫 In short, the reason you can't use Some(Path::new(".")) is because Path::new(".") is not a pattern .简而言之,您不能使用Some(Path::new("."))的原因是因为Path::new(".")不是pattern

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

However, in that particular case you could also just use an if expression like this:但是,在那种特殊情况下,您也可以只使用 if 表达式,如下所示:

if my_path.parent() == Some(Path::new(".")) {
    // Do something.
} else {
    // Do something else.
}

Two options, convert the path into a str or use a match guard.两个选项,将path转换为str或使用匹配守卫。 Both examples below:下面两个例子:

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 操场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM