【发布时间】:2023-03-29 17:30:01
【问题描述】:
我正在编写一些使用 ? 运算符的 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()? 的值初始化了一个变量,我得到了同样的错误。
【问题讨论】:
-
您要返回的
Error类型是什么?OsString很可能无法转换成它,因为into_string在出错的情况下会返回原始的OsString。
标签: rust