Should trait bounds be duplicated in struct and impl?

后端 未结 2 1076
予麋鹿
予麋鹿 2020-12-06 09:45

The following code uses a struct with generic type. While it\'s implementation is only valid for the given trait bound, the struct can be defined with or without the same bo

2条回答
  •  北海茫月
    2020-12-06 10:06

    Trait bounds that apply to every instance of the struct should be applied to the struct:

    struct IteratorThing
    where
        I: Iterator,
    {
        a: I,
        b: Option,
    }
    

    Trait bounds that only apply to certain instances should only be applied to the impl block they pertain to:

    struct Pair {
        a: T,
        b: T,
    }
    
    impl Pair
    where
        T: std::ops::Add,
    {
        fn sum(self) -> T {
            self.a + self.b
        }
    }
    
    impl Pair
    where
        T: std::ops::Mul,
    {
        fn product(self) -> T {
            self.a * self.b
        }
    }
    

    to conform to the DRY principle

    The redundancy will be removed by RFC 2089:

    Eliminate the need for “redundant” bounds on functions and impls where those bounds can be inferred from the input types and other trait bounds. For example, in this simple program, the impl would no longer require a bound, because it can be inferred from the Foo type:

    struct Foo { .. }
    impl Foo {
      //    ^^^^^ this bound is redundant
      ...
    }
    

提交回复
热议问题