繁体   English   中英

如何模式匹配 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

我阅读了 Rust 书中的第 18 章,但我无法弄清楚如何使用PathPathBuf类型修复我的特定场景。

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

如果你想使用match ,那么你可以使用火柴后卫 简而言之,您不能使用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
        }
    }
}

操场

暂无
暂无

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

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