#Implement foreign trait for generic, requiring own trait

5 messages · Page 1 of 1 (latest)

keen radish
#
struct Foo {

}

impl Bar for Foo {
    fn random_function() -> bool {
        false
    }
}

trait Bar {
    fn random_function() -> bool;
}

impl<T> Debug for T where T: Bar {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        if T::random_function() {
            // do stuff
        };
        todo!()
    }
}

I created the minimal example above, which is rejected by the compiler with:

error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g., `MyStruct<T>`)
   --> FILE
    |
190 | impl<T> Debug for T where T: Bar {
    |      ^ type parameter `T` must be used as the type parameter for some local type
    |
    = note: implementing a foreign trait is only possible if at least one of the types for which it is implemented is local
    = note: only traits defined in the current crate can be implemented for a type parameter

Does anyone know, if it is possible to achieve this thing somehow?
(The actual implementation is more code, but the trait still does only return true or false, and the result depends on the actual type of the generic)

#

The idea is, that I have multiple types, all implementing a foreign trait (Debug in the example), and all work exactly the same, but the one if condition is different for all types.
So my idea is, to take that condition, move it into another trait and require that trait.

#

I could also create a declarative macro, which does nothing than copying the if condition into the impl block at the correct location. But then I need a macro, and the example above does not need a macro 🤷

keen radish