如何将Box <dyn错误+同步+发送>转换为Box <dyn错误>

时间:2019-12-01 23:24:40

标签: rust

在我的程序中,一些操作是在辅助线程上执行的,其结果: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>>

我知道可以通过创建包装器来完成此操作,但是我不想添加下一级的间接访问。

1 个答案:

答案 0 :(得分:-1)

如何在这两种类型之间进行转换的问题仍然悬而未决。

现在,我切换到https://crates.io/crates/failure板条箱进行错误处理,其中Error类型替换了Box<dyn Error + Sync + Send>,也使创建自定义和字符串(甚至格式化的)错误变得容易。

相关问题