【发布时间】:2019-05-27 18:12:08
【问题描述】:
我可以在接受Box<dyn Error> 的地方接受Box<dyn Error + Send> 吗?如果是,如何?如果不是,为什么?有没有比下面的例子更优雅的方法?
#![allow(unused)]
use std::error::Error as StdError;
use std::result::Result as StdResult;
type Result = StdResult<(), Box< dyn StdError >>;
type SndResult = StdResult<(), Box< dyn StdError + Send >>;
fn fn_returning_result() -> Result { Ok(()) }
fn fn_returning_sndresult() -> SndResult { Ok(()) }
/// Accept a callback that returns a non-Send `Result`.
fn register_callback<CB: FnOnce() -> Result>(cb: CB) { /* ... */ }
fn main() -> Result {
// Is there a way to get rid of ... vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv ... this part?
let cb = || fn_returning_sndresult().map_err(|e| -> Box<dyn StdError> { e });
register_callback(cb);
Ok(())
}
编辑:我想在这里做的只是let cb = || fn_returning_sndresult();,但这不会编译。
另外,我想在回调中调用 fn_returning_result()? 或 fn_returning_sndresult()? 并使用单一返回类型而不执行 map_err。
【问题讨论】:
-
在浏览 Google 结果时,我遇到了以下问题:Send/Sync additional trait requirements cannot be automatically relaxed。它基本上说
Box<dyn Error + ...> => Box<dyn Error>coercion 已被删除,但我仍然不确定作为用户该怎么做。
标签: rust