【问题标题】:How can I specify the same trait bounds on two generic types? [duplicate]如何在两个泛型类型上指定相同的特征界限? [复制]
【发布时间】:2022-12-15 17:19:16
【问题描述】:

我的方法需要它的两个泛型类型具有相同的特征界限, 有什么办法可以不重复的写吗?

fn value(&mut self, arg: U) -> V 
    where
    U: std::cmp::Eq + std::hash::Hash, 
    V: std::cmp::Eq + std::hash::Hash, 
{

【问题讨论】:

    标签: rust


    【解决方案1】:

    你不能给特征边界起别名,但是你可以用一些超级特征创建一个特征,并添加一个全面的实现:

    // You can only implement Foo on types that also implement Debug and Clone
    trait Foo: Debug + Clone {}
    
    // For any type that does implement Debug and Clone, implement Foo
    impl<T> Foo for T where T: Debug + Clone {}
    

    通过这些行,您现在拥有了一个新特征 Foo,它会自动为同时也是 DebugClone 的任何类型实现。然后你可以使用Foo作为你的特征界限,它会像你写的那样:T: Debug + Clone

    【讨论】:

      猜你喜欢
      • 2021-10-20
      • 1970-01-01
      • 2023-01-12
      • 1970-01-01
      • 2021-07-02
      • 1970-01-01
      • 1970-01-01
      • 2016-04-10
      • 2022-10-05
      相关资源
      最近更新 更多