Search code examples
ruststructtraits

Rust not finding method of trait struct because of lifetime parameters


I was trying to do simple struct with few traits following examples on the internet an came across the following problem.

//My struct in framebuffer.rs
pub struct HighLevelFrameBuffer<'a> {
    pub fbinfo: FrameBufferInfo,
    pub fbdata: &'a mut [u8],
    pub pixel_bytesize: u8,
    pub color: FrameBufferColor,
}
//Trait and implementation
trait WriteLine {
    fn write_line(&self, line: usize, color: FrameBufferColor);
}
impl<'a> WriteLine for HighLevelFrameBuffer<'a> {

    fn write_line(&self, line: usize, color: FrameBufferColor) {
        //Do stuff
    }
}

When I try to call this from my main function as follows from main.rs:

mod framebuffer;
pub use framebuffer::HighLevelFrameBuffer;
pub use framebuffer::FrameBufferColor;

let hlfb = HighLevelFrameBuffer{
    fbinfo: something,
    fbdata: data_location,
    pixel_bytesize: 0,
    color:  FrameBufferColor {r: 0, g: 0, b: 0}
};
hlfb.write_line(100, FrameBufferColor{r: 0xFF, g: 0xFF, b: 0xFF});

Compiler tells me that there is no implementation of write_line for HighLevelFrameBuffer struct:

hlfb.write_line(100, FrameBufferColor{r: 0xFF, g: 0xFF, b: 0xFF});
   |          ^^^^^^^^^^ method not found in `HighLevelFrameBuffer<'_>` 
pub struct HighLevelFrameBuffer<'a> {
   | ----------------------------------- method `write_line` not found for this struct

What I am doing wrong here?


Solution

  • There could be a couple reasons for this:

    1. Did you make a typo when typing write_line?
    2. Is WriteLine defined in a different file from where you're calling hlfb.write_line? If it is, then have you added a use statement to import WriteLine?

    It's hard to be more specific without more details.