Rust:缩短泛型类型边界

Kra*_*ser 3 generics rust

有没有办法缩短 Rust 中的泛型类型边界?这是我必须放置很多结构体实现等的混乱:

pub struct IncomingClientMessageWithAddress<State, Msg>
    where State: AppState + Clone + serde::Serialize + serde::de::DeserializeOwned + std::marker::Unpin + 'static,
          Msg: AppEvent + Clone + serde::Serialize + serde::de::DeserializeOwned + std::marker::Unpin + 'static {
...
Run Code Online (Sandbox Code Playgroud)

我基本上希望做这样的事情(我知道以下不适用于特征):

type MyStateAlias = AppState + Clone + serde::Serialize + serde::de::DeserializeOwned + std::marker::Unpin + 'static;
type MyEventAlias = AppEvent + Clone + serde::Serialize + serde::de::DeserializeOwned + std::marker::Unpin + 'static;


pub struct IncomingClientMessageWithAddress<State, Msg>
    where State: MyStateAlias,
          Msg: MyEventAlias {
...
Run Code Online (Sandbox Code Playgroud)

phi*_*mue 5

我有时意识到某个特征的所有出现都与其他特征相关。在您的情况下,如果AppState 总是Cloneand 一起出现Serialize,您可能已经在状态之上需要这些:

trait AppState : Clone + Serialize {/*...*/}
Run Code Online (Sandbox Code Playgroud)

如果没有,你仍然可以定义一个辅助特征

trait AuxAppState: AppState + Clone + Serialize {/*...*/}
Run Code Online (Sandbox Code Playgroud)

并要求State : AuxAppState.

然后,自动地得到AuxAppState你不得不impl它为每个类型也impl对此语句StateClone以及Serialize

impl<T> AuxAppState for T where T: AppState + Clone + Serialize {}
Run Code Online (Sandbox Code Playgroud)

最后,定义和implementing的AuxAppState可能会因一个完成宏来节省一些按键

macro_rules! auxiliary_trait{
    ($traitname: ident, $($t:tt)*) => {
        trait $traitname : $($t)* {}
        impl<T> $traitname for T where T: $($t)* {}
    }
}
Run Code Online (Sandbox Code Playgroud)

所有这一切都可能有一天用trait aliases来完成。

此外,我开始只在真正需要的地方才需要 trait bound。例如,在许多情况下, -struct定义本身不依赖于 trait bound,只依赖于impl,所以我开始在 the 上省略它们struct,只将它们保留在impl.