Okay to use unwrap() when I'm sure variable is Some?

I know using unwrap() is considered bad practice but is it okay to use in this code?

    let path_str = "some/path/to/file.txt";
    let path = std::path::Path::new(path_str);
    std::fs::create_dir_all(path.parent().unwrap())?;

Because path_str is hard-coded I am sure it has a parent() and won't be None. Is unwrap() okay here?

Personally I think that is fine, but if it bothers you, you could do this instead:

let dir = Path::new("some/path/to");
std::fs::create_dir_all(dir)?;
let path = dir.join("file.txt");
4 Likes

Yes. It's even preferable to ?, in my opinion.

It's basically this case, from Using unwrap() in Rust is Okay - Andrew Gallant's Blog

Is it a bug if the program couldn’t build a regular expression from a static string literal? Yup. The programmer typed that regex. It should be correct. So a panic is appropriate.

7 Likes

I still find this ugly.

The only time I find unwrapping tolerable is when I personally put a literal Some in an optional just before the unwrap, so that it's blatantly obvious there will be no possibility for panic.

In the above case, you are instead relying on a computation (getting the parent of a path) behaving in a particular way and returning a particular value. That's pretty fragile.

You should indeed invert the dependency and compute the child from the parent, not the other way around.

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.