How to minimize trait bounds repetition?

Question 1: here's some code I wrote, and it compiles, but I wonder if it's possible to write these trait bounds less times than I did? The compiler doesn't require them in type declaration, but on docs.rs every type with generics does have them. Should I keep them there?

pub trait IntoDuration {};
pub struct RawEdge {};

pub struct WeightedEdge<S: IntoDuration> {
    speed: S
}

impl<S: IntoDuration> WeightedEdge<S> {
    pub fn from_raw(de: &RawEdge) -> Self {
        todo!()
    }
}

pub struct Graph<S: IntoDuration> {
    edges: Vec<WeightedEdge<S>>,
}

impl<S: IntoDuration> Graph<S> {
    // take denorm edge, convert
    pub fn try_build<I>(&mut self, edges: I) -> Result<(), Box<dyn Error>> where I: Iterator<Item = RawEdge>, S: IntoDuration {
        todo!()
    }

}

Question 2: what to do if you need multiple traits and want to avoid repetition?

impl<'a, V: Copy + Hash + Eq, T: Clone> Iterator ...
//       ^^^^^^^^^^^^^^^^^^^
//       at least, maybe there's an alias for multiple traits?

Don't require bounds when they are not necessary. In the overwhelming majority of cases, they are not necessary on type declarations themselves. (The only exceptions I know of are when you want to use an associated type from a type parameter, or when you want to allow ?Sized.)

Your second question was answered yesterday.

4 Likes

Another case where they are necessary on the type declaration is when you want to use methods from the trait in the Drop impl.

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.