Where to put the trait-definition

I'm trying to make an abstract interface between a led-driver (ws28xx) and a led-lib, that paints the colors on the led-strip. So I've made a trait:

pub trait WriteLedRGB {
    fn write_led_rgb(&mut self, r: u8, g: u8, b: u8) -> ();
}

I dropped the trait in the led-lib currently, and it compiles and works.
My instinct now tells me to put the trait in a file of itself. led_traits.rs.
(The driver can exist without the lib, and vice versa. Also, there can exist many drivers and many lib-files, so they should not redefine it)

But by doing so, I cant figure out to write the use/mod statements correctly.

If I do this in the driver:

mod led_traits
use led_traits::WriteLedRGB

And then implement the trait, I will have implemented

driver::led_traits::WriteLedRGB

And doing the same in the lib, i will have used:

ledlib::led_traits::WriteLedRGB

And that is not the same, so the compiler gets angry about the trait bounds not satisfied.

How do I approach this correctly?

Thx
/Troels

Hey can you fence your code blocks with 3 backticks ``` - makes it much easier to read. :slight_smile:

And see the pinned formatting post for more details.

What's the overall layout of your project? When you say that these are different:

driver::led_traits::WriteLedRGB
ledlib::led_traits::WriteLedRGB

I'm getting the impression that you're either including the same led_traits module file in two separate crates, or including the same led_traits module file in two different paths within the same crate.


In a more general sense, I'm guessing that you're thinking of having one library (ledlib) that supports many different drivers. If that's the case, I would define the trait in the ledlib crate, and each driver that wants to interoperate would implement the trait. You could put this implementation behind a feature flag if you wanted to be able to build the driver without the ledlib dependency. The main alternative is that the ledlib would implement the trait for each driver.

If the trait is genuinely useful on it's own, a separate crate both ledlib and drivers depend on is another alternative.

(I'm not entirely sure this is what you meant because you also said that there may be "many lib-files", and I don't know how to interpret that.)

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.