简体   繁体   中英

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.

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") ?

If you want to use a match , then you can use a match guard . In short, the reason you can't use Some(Path::new(".")) is because Path::new(".") is not a 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 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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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