Hi, I am very new to rust and have a problem with an implementation using generics.
I have a "complex" implementation that I want to be reused for two different types only.
Therefore I use a generic type and limit it to "Vec3" and "f32" by using a trait.
The problem is that I need different logic at one place for the specific type. I tried to provide implementations for both of the possible types, but the compiler complains that it cannot find the function with the generic.
I prepared a working example (playground) that compiles, but lags the possibility to differentiate between the generic type.
variant 1: compiles, but cannot separate logic
variant 2: compile error, but separate logic
variant 1+2: compile error (conflicting implementation)
Maybe there is a totally other way of achieving this? Enums for the rescue? I would appreciate help and advises, here.
Thanks!
I don't know whether this is actually what you want, though. I don't understand what the difference between the two FileLoader impls is supposed to be, because there is none. Also, in general, if you want to differentiate behavior based on types implementing a common trait, then you should put that behavior as a method into the trait, and the trait impls should differ, instead of special-casing impls of a second trait for different, concrete specializations of a given generic type.
I don't know whether this is actually what you want, though.
Yes, that's exactly what I wanted. And after seeing the solution it seems obvious to me
I don't understand what the difference between the two FileLoader impls is supposed to be, because there is none.
The given example is boiled down to the bare minimum and I skipped implementation details. My real implementation needs to handle image data and indexing/offsetting depending on the number of color channels.
if you want to differentiate behavior based on types implementing a common trait, then you should put that behavior as a method into the trait, and the trait impls should differ
In my real world case the ImageTexture already implements a trait Texture<T: ColorComp> (missing in the example). Therefore I created another independant trait (FileLoader) that is only responsible for the file loading, as other textures don't need it.