Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What kind of lifetime parameter do I have to use here when declaring a struct field object type

This is what my code looks like. I'm trying to use a impled struct within my ShapeRenderer struct and use its methods.

shapes.rs:

use super::core::*;

pub struct ShapeRenderer<'a> {
    core_renderer: &'a mut CanvasRenderer,
}

core.rs

pub struct Canvas {
    pub width: usize,
    pub height: usize,
    pub array: Vec<char>,
}

pub struct Point {
    pub x: usize,
    pub y: usize,
}

pub struct CanvasRenderer<'a> {
    canvas: &'a mut Canvas,
}

impl<'a> CanvasRenderer<'a> {
    pub fn new(canvas: &'a mut Canvas) -> CanvasRenderer {
        CanvasRenderer { canvas: canvas }
    }
}

Error

error[E0107]: wrong number of lifetime parameters: expected 1, found 0
 --> src/shapes.rs:5:28
  |
5 |     core_renderer: &'a mut CanvasRenderer
  |                            ^^^^^^^^^^^^^^ expected 1 lifetime parameter

I marked it with a lifetime parameter - why does it want another one? tried the object type with <'a> and appended it <'a> - neither of those attempts solved the problem.

like image 441
xetra11 Avatar asked Aug 24 '16 15:08

xetra11


1 Answers

CanvasRenderer is parameterized over a lifetime, so you need to state what that lifetime is:

pub struct ShapeRenderer<'a> {
    core_renderer: &'a mut CanvasRenderer<'a>,
    //                                   ^^^^
}

However, this structure doesn't seem to have much purpose, it only adds indirection. Why have a reference to a thing that only has a reference? Skip the middleman:

pub struct ShapeRenderer<'a> {
    core_renderer: CanvasRenderer<'a>,
}
like image 172
Shepmaster Avatar answered Oct 18 '22 22:10

Shepmaster