Dependend trait def problem

Suppose I have this

pub trait A {
    type valueA;
    fn foo(&Self) -> bool;
}

pub trait B<T:A> {
    type valueB;    
    fn bar(&Self::valueA) -> valueB;
}

And I want to do something like this:

pub trait traid_collection: A + B <A> + ... more traits {
    type version;
}

impl <T> traid_collection for T
    where T: A + B<A> + more traits
{ 
        type version = u64;
}

This does not compile. The reason to use trait_collection is to make change in the amount and dependencies of the traits in the system more manageable. It there a way to get this to compile? The idea arose from a discussion here: Messy generic type dependencies

pub trait A {
    type ValueA;
    fn foo(&self) -> bool;
}

pub trait B<T:A> {
    type ValueB;    
    fn bar(_: &T::ValueA) -> Self::ValueB;
}

pub trait Traits<T: A>: A + B<T> + Send + Sync {
    type Version;
}

impl <T, U: A> Traits<U> for T
    where T: A + B<U> + Send + Sync
{ 
        type Version = u64;
}

Unfortunately this defies the entire purpose of trait-collection. We don't want many type parameters but capture everything inside a single one.

The reason is, that everytime the code base advances and a new trait appears that might depend complicated on other traits and generics, one must rewrite the signuters of all types that depend on this. This is not fixable locally (inside a single file) but requires changes on many files.

Different types can implement trait B<T> for different T's. You can't capture that in a single umbrella trait.

1 Like

Then how do programmers handle this without tweaking the entire dependent codebase everytime a new trait appears?

It does not depend on the type only on the trait bound of that type, so the type can stay abstract

No it can't, using an associated type is not just using the trait bound. It can play into layouts, so you can't just erase the type. That's not how dynamic dispatch works.

@red75prime's solution does make things simpler because you only need to refer to the umbrella trait instead of all it's parts.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.