Why does str::strip_prefix() returns an Option?

Hey, I have a Vec<PathBuf>, where some PathBufs can start with "./" prefix. I tried to iterate them like this, but realized it would not work:

let infiles: Vec<PathBuf> = ...
let to_edit = infiles
    .iter()
    .map(|inf| inf.strip_prefix("./").to_string_lossy())
    .collect::<Vec<_>>();

To make it work, I had to rewrite it like this:

let infiles: Vec<PathBuf> = ...
let to_edit = infiles
    .iter()
    .map(|inf| {
        if inf.starts_with("./") {
            inf.strip_prefix("./").unwrap()
        } else {
            inf
        }
        .to_string_lossy()
    })
    .collect::<Vec<_>>();

So, I have two questions:

  1. Is there a more elegant way to write that snippet?
  2. Do you see a good reason for str::strip_prefix() to return an Option<&'a str> instead of returning &'a str? I see it causing inconvenience, but what is the benefit?

Is same as:

inf.strip_prefix("./").unwrap_or(inf)

Path::strip_prefix() fails if the original path doesn't starts with given prefix.

2 Likes

That is very elegant, thank you!

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.