【发布时间】:2018-05-09 20:28:48
【问题描述】:
Crius 库提供
Rust 的类似断路器的功能。 Crius 定义了一个名为 Command 的结构,如下所示:
pub struct Command<P, T, CMD>
where
T: Send,
CMD: Fn(P) -> Result<T, Box<CommandError>> + Sync + Send,
{
pub config: Option<Config>,
pub cmd: CMD,
phantom_data: PhantomData<P>,
}
是否可以将Command 的实例作为字段存储在不同的结构中?
我开始尝试从 功能。简单地实例化类型是没有问题的:
/// This function constructs a simple instance of `Command<P, T, CMD>` with the
/// types set to:
///
/// P ~ u8
/// T ~ u8
/// CMD: Fn(u8) -> Result<u8, Box<CommandError>> + Send + Sync
///
/// This function compiles fine. However, there is no *concrete* type
/// for `CMD`. In compiler output it will be referred to as an
/// "anonymous" type looking like this:
///
/// Command<u8, u8, [closure@src/lib.rs:19:21: 19:38]>
fn simple_command_instance() {
let _ = Command::define(|n: u8| Ok(n * 2));
}
为 功能:
fn return_command_instance() -> Command<u8, u8, ???> {
^
|
What goes here? -------
Command::define(|n: u8| Ok(n * 2))
}
编译器推断的类型是匿名的——不能放入
那里。很多时候,当关闭时,人们诉诸于
使用Box<F: Fn<...>>,但是没有实现
impl Fn<T> for Box<Fn<T>> - 所以装箱类型会破坏
crius::command::Command 给出的约束。
在具有新 impl Trait 功能的 Rust 版本中(例如
即将发布的稳定版本),这是可能的:
/// Use new `impl Trait` syntax as a type parameter in the return
/// type:
fn impl_trait_type_param() -> Command<u8, u8, impl Fn(u8) -> Result<u8, Box<CommandError>>> {
Command::define(|n: u8| Ok(n * 2))
}
这在稳定的 Rust 中不起作用,impl Trait 只能
用于返回类型,而不是结构成员。
尝试传播泛型类型最终看起来像 这个:
fn return_cmd_struct<F>() -> Command<u8, u8, F>
where
F: Fn(u8) -> Result<u8, Box<CommandError>> + Send + Sync,
{
Command::define(|n: u8| Ok(n * 2))
}
但这不能编译:
error[E0308]: mismatched types
--> src/lib.rs:33:21
|
33 | Command::define(|n: u8| Ok(n * 2))
| ^^^^^^^^^^^^^^^^^ expected type parameter, found closure
|
= note: expected type `F`
found type `[closure@src/lib.rs:33:21: 33:38]`
同样,我不知道如何在 结果签名。
即使将类型作为泛型参数进行传播,它也会
对于我们的特定用例来说仍然是一个问题。我们想存储一个
Command 作为 actix 演员的一部分,该演员注册为
SystemService,这需要一个 Default 实现,它
最终再次迫使我们提供具体类型。
如果有人对可能的方法有任何想法,请分享 他们。绝对知道它不可能也很好。
【问题讨论】: