Convert Option<&str> to Option<PathBuf>

use clap::{App, Arg, ArgMatches};
use std::path::PathBuf;

struct CmpOptions {
    file1: PathBuf,
    file2: Option<PathBuf>,
}

impl CmpOptions {
    fn new(matches: ArgMatches) -> Self {
        Self {
            file1: matches.value_of("file1").unwrap().into(),
            file2: matches.value_of("file2"),
        }
    }
}

fn main() {
    println!("Hello");
}

fn parse_command_line() -> CmpOptions {
    let matches = App::new("cmpr")
        .arg(
            Arg::with_name("file1")
            .required(true)
            .index(1),
        )
        .arg(
            Arg::with_name("file2")
            .index(2),
        )
        .get_matches();

     CmpOptions::new(matches)
}
13 |             file2: matches.value_of("file2"),
   |                    ^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `PathBuf`, found `&str`
   |
   = note: expected enum `Option<PathBuf>`
              found enum `Option<&str>`

How can I convert from Option<&str> to Option please?

Thanks.

I think you can use .map(PathBuf::from).

use std::path::PathBuf;

fn main() {
    let x: Option<&str> = Some("new");
    let _y: Option<PathBuf> = x.map(PathBuf::from);
}

(Playground)

3 Likes

If you want to generically convert an Option<T> into an Option<U> (and not be specific to PathBuf but rely on type inference instead), you could also consider .map(Into::into).

    let _y: Option<PathBuf> = x.map(Into::into);

(Playground)

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.