![](/img/trans.png)
[英]How to accept `Box<dyn Error + Send>` in places that accept `Box<dyn Error>`?
[英]How to convert Box<dyn Error + Sync + Send> to Box<dyn Error>
在我的程序中,一些操作是在辅助线程上执行的,它们的结果: Result<(), Box<dyn Error>>
被发送回主线程。 对于具有Send
要求的错误来说,这是非常合理的,因此实际类型是Result<(), Box<dyn Error + Send>>
。 我还添加了Sync
以便能够使用Box
from
方法(仅针对普通或同步 + 发送实现)。 但是在单线程上确定结果后,我想放弃这个要求。
例子:
use std::error::Error;
fn test1() -> Result<(), Box<dyn Error + Sync + Send>> {
return Err("test1".into());
}
fn test2() -> Result<(), Box<dyn Error>> {
test1()?;
return Ok(());
}
fn main() {
let test2_result = test2();
println!("test2_result: {:#?}", test2_result);
}
最后我实际上以:
Compiling playground v0.0.1 (/playground)
error[E0277]: the size for values of type `dyn std::error::Error + std::marker::Send + std::marker::Sync` cannot be known at compilation time
--> src/main.rs:7:12
|
7 | test1()?;
| ^ doesn't have a size known at compile-time
|
= help: the trait `std::marker::Sized` is not implemented for `dyn std::error::Error + std::marker::Send + std::marker::Sync`
= note: to learn more, visit <https://doc.rust-lang.org/book/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 + std::marker::Send + std::marker::Sync>`
= note: required because of the requirements on the impl of `std::convert::From<std::boxed::Box<dyn std::error::Error + std::marker::Send + std::marker::Sync>>` for `std::boxed::Box<dyn std::error::Error>`
= note: required by `std::convert::From::from`
error: aborting due to previous error
For more information about this error, try `rustc --explain E0277`.
error: could not compile `playground`.
To learn more, run the command again with --verbose.
这些类型似乎不兼容。
那么如何将(例如在test2
) Result<(), Box<dyn Error + Send>>
为Result<(), Box<dyn Error>>
?
我知道这可以通过创建包装器来完成,但我不想添加下一个间接级别。
如何在这两种类型之间转换的问题仍然存在。
现在我切换到https://crates.io/crates/failure crate 进行错误处理,其中Error
类型替换了Box<dyn Error + Sync + Send>
,还可以轻松创建自定义和字符串(甚至格式化)错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.