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

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-01 20:47:47

问题


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.


回答1:


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>,
}


来源:https://stackoverflow.com/questions/39127218/what-kind-of-lifetime-parameter-do-i-have-to-use-here-when-declaring-a-struct-fi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!