Advice on how to deal with immense ~const trait bounds?

I'm currently working on a small project containing various generic const fns. These functions all share the same trait bounds, and they are huge.

Trying to cut down on the duplication of these bounds, i tried the following:

  • A macro-based solution

    • Too clunky, since it cannot be called from a generic bounds context
    • I'll stick with this solution if everything else fails
  • The nightly trait_alias feature

    • Doesn't yet support multiple non-marker traits, which I need
  • Manually creating a trait and making a blanket impl

    • The trait definition's bounds cannot contain ~const bounds, which I need
  • Manually making a trait with a blanket statement without the ~const bounds, rather specifying the trait alias as ~const in each function that uses it

    • If a bound specifies a ~const trait, the supertraits are not considered to be ~const, achieving nothing.

Is there any alternative to these solutions I'm not seeing?
If not, maybe an upcoming feature to help out with this issue?

Can you show us an example of one of these complicated bounds? It might be that there's a trick we can use that works for your specific use case. The problem with asking general questions is we can only really give you general answers.

In general, my opinion is that overly complex generics are a code smell. Sure, we could hide the details with a trait alias or some macro magic, but that doesn't fix the underlying problem that we have lots of complex requirements all spelled out separately. I don't have any hard and fast rules, but I would hypothesize that the difficulty of using (and maintaining!) a function is exponentially proportional to the size of its where-clause.

Maybe there's a more general abstraction buried under all those trait bounds or maybe we're actually being more specific than we need to be? It could also be time to encapsulate some of those implementation details behind a level of indirection (i.e. type erasure via trait objects or a trait with associated constants). Normally when I get into a situation like this, the first thing I'll do is take a step back and ask if I'm overcomplicating things and whether I could have an easier time by going back to the drawing board.

1 Like