【发布时间】:2019-03-12 13:24:00
【问题描述】:
这是我的测试代码:
use std::error::Error;
use std::fmt;
struct Handler {
error: String
}
#[derive(Debug)]
struct SpecificError;
impl fmt::Display for SpecificError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "SpecificError")
}
}
impl Error for SpecificError {}
impl<E: Error> From<E> for Handler {
fn from(e: E) -> Self {
Handler { error: format!("{}", e) }
}
}
fn fail1() -> Result<(), SpecificError> {
Err(SpecificError)
}
fn fail2() -> Result<(), Box<Error>> {
Err(Box::new(SpecificError))
}
fn handler() -> Result<(), Handler> {
fail1()?;
fail2()?;
Ok(())
}
对fail1() 的调用很好,但对fail2() 的调用无法编译:
error[E0277]: the size for values of type `dyn std::error::Error` cannot be known at compilation time
--> src/main.rs:35:5
|
35 | fail2()?;
| ^^^^^^^^ doesn't have a size known at compile-time
|
= help: the trait `std::marker::Sized` is not implemented for `dyn std::error::Error`
= note: to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>
= note: required because of the requirements on the impl of `std::error::Error` for `std::boxed::Box<dyn std::error::Error>`
= note: required because of the requirements on the impl of `std::convert::From<std::boxed::Box<dyn std::error::Error>>` for `Handler`
= note: required by `std::convert::From::from`
我同意编译器dyn Error 在编译时没有已知大小,但我不明白为什么这是相关的,因为我尝试转换的类型是Box<dyn Error>,它确实有一个在编译时已知的大小。
【问题讨论】:
标签: rust