【发布时间】:2020-03-26 14:16:52
【问题描述】:
在我的程序中,在辅助线程上执行了一些操作及其结果: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>>?
我知道这可以通过创建包装器来完成,但我不想添加下一级间接。
【问题讨论】:
-
if let Err(e) = test1() { return Err(e);}可以工作。 -
看来向上转换 trait 对象是个问题,见stackoverflow.com/questions/28632968/…
标签: rust