繁体   English   中英

为什么没有盒子<dyn std::error::error>捕获 std::string::FromUtf8Error</dyn>

[英]Why doesn't Box<dyn std::error::Error> capture std::string::FromUtf8Error

我在下面有一个简单的程序,它试图通过String String::from_utf8打印从硬编码的Vec创建的字符串。

我也在这里使用类型别名来减少冗长(例如Result<String, SomeError> vs 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

在一种情况下你有FromUtf8Error ,在另一种情况下你有Box<Stuff> Stuff完全无关紧要,Rust 从不隐式地投射或装箱。 如果要转换错误,请使用? 操作员。 该运算符尝试转换错误类型,并且可以进行错误装箱:

fn foo() -> Result<String> {
    let vec = vec![65; 3];
    Ok(String::from_utf8(vec)?)
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM