Rust - the trait `StdError` is not implemented for `OsString`

Viewed 2075

I'm writing some Rust code which uses the ? operator. Here is a few lines of that code:

fn files() -> Result<Vec<std::string::String>, Box<Error>> {

    let mut file_paths: Vec<std::string::String> = Vec::new();
    ...
    file_paths.push(pathbuf.path().into_os_string().into_string()?);
    ...
    Ok(file_paths)
}

However, even though I'm using ? on a Result it is giving me the following error:

`the trait `StdError` is not implemented for `OsString`.

This is contrary to the Rust documentation here, which states that:

The ? is shorthand for the entire match statements we wrote earlier. In other words, ? applies to a Result value, and if it was an Ok, it unwraps it and gives the inner value. If it was an Err, it returns from the function you're currently in.

I've confirmed that pathbuf.path().into_os_string().into_string() is of type Result, because when I remove the ?, I get the following compiler error:

expected struct `std::string::String`, found enum `std::result::Result`

(since file_paths is a Vector of strings, not Results).

Is this a bug with the Rust language or documentation?

In fact I tried this without pushing to the Vector, but simply initializing a variable with the value of pathbuf.path().into_os_string().into_string()?, and I got the same error.

1 Answers

The function OsString::into_string is a little unusual. It returns a Result<String, OsString> - so the Err variant is actually not an error.

In the event that the OsString cannot be converted into a regular string, then the Err variant is returned, containing the original string.

Unfortunately this means you cannot use the ? operator directly. However, you can use map_err to map the error variant into an actual error, like this:

file_paths.push(
    pathbuf.path()
    .into_os_string()
    .into_string().
    .map_err(|e| InvalidPathError::new(e))?
);

In the above example, InvalidPathError might be your own error type. You could also use an error type from the std library.

Related