下面我有一个简单的程序,它试图通过String打印一个从硬编码的Vec创建的String::from_utf8。
我也在这里使用类型别名来减少冗长(例如Result<String, SomeError>和Result<String>)。
use std::error;
use std::result;
pub type Error = Box<dyn error::Error>;
pub type Result<T> = result::Result<T, Error>;
fn main() {
let vec = vec![65; 3];
let text = String::from_utf8(vec).unwrap();
println!("result {}", text);
}
fn foo() -> Result<String> {
let vec = vec![65; 3];
String::from_utf8(vec)
}但是,程序没有编译,我得到了以下错误:
|
26 | fn foo() -> Result<String> {
| -------------- expected `std::result::Result<String, Box<(dyn std::error::Error + 'static)>>` because of return type
27 | let vec = vec![65; 3];
28 | String::from_utf8(vec)
| ^^^^^^^^^^^^^^^^^^^^^^ expected struct `Box`, found struct `FromUtf8Error`
|
= note: expected enum `std::result::Result<_, Box<(dyn std::error::Error + 'static)>>`
found enum `std::result::Result<_, FromUtf8Error>`我想知道有没有人知道为什么这不管用。我本以为Box<dyn error::Error>会捕获所有错误,但是看起来FromUtf8Error是一个例外(或者我只是误解了什么)。是否有办法将自定义Result别名调整为一般捕获FromUtf8Error
发布于 2022-01-01 15:07:22
在一种情况下,您有FromUtf8Error,在另一种情况下,您有Box<Stuff>。Stuff是完全不相关的,Rust从不隐式地抛出或装箱任何东西。如果要转换错误,请使用?运算符。此操作符尝试转换错误类型,并可以执行错误装箱:
fn foo() -> Result<String> {
let vec = vec![65; 3];
Ok(String::from_utf8(vec)?)
}https://stackoverflow.com/questions/70549331
复制相似问题