我正在编写一些使用 ?
运算符的 Rust 代码。这是该代码的几行:
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)
}
但是,即使我在 ?
上使用 Result
,它也会给我以下错误:
`the trait `StdError` is not implemented for `OsString`.
这与 Rust 文档 here 相悖,它指出:
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.
我已经确认 pathbuf.path().into_os_string().into_string() 是 Result
类型,因为当我删除 ?
时,我收到以下编译器错误:>
expected struct `std::string::String`, found enum `std::result::Result`
(因为 file_paths 是字符串向量,而不是结果)。
这是 Rust 语言或文档的错误吗?
事实上,我在没有推送到 Vector 的情况下尝试了这个,只是简单地用 pathbuf.path().into_os_string().into_string()?
的值初始化了一个变量,我得到了同样的错误。
答案 0 :(得分:3)
函数 OsString::into_string 有点不寻常。它返回一个 Result<String, OsString>
- 所以 Err
变体实际上不是错误。
如果 OsString
无法转换为常规字符串,则返回 Err
变体,其中包含原始字符串。
不幸的是,这意味着您不能直接使用 ?
运算符。但是,您可以使用 map_err
将错误变体映射为实际错误,如下所示:
file_paths.push(
pathbuf.path()
.into_os_string()
.into_string().
.map_err(|e| InvalidPathError::new(e))?
);
在上面的示例中,InvalidPathError
可能是您自己的错误类型。您还可以使用 std 库中的错误类型。