1

I love rust and I want to master it, but I am having difficulties.

Surely its about lifetimes. I still have a hard time getting my head around it yet. I show you some code here. There you can see a struct which holds a borrowed array.

When creating the CTOR for that Canvas I fail in declaring the lifetime 'a the right way.

struct Canvas<'a>{ 
  width: i32,
  height: i32, 
  array: &'a Vec<char>
}

impl <'a>Canvas<'a>{
  fn new(width: i32, height: i32) -> Canvas<'a>{
    Canvas {
      width: width,
      height: height,
      array: &vec!['x'; (width*height) as usize]
  }
}

Error says:

Reference must be valid for the lifetime 'a as defined on the block at 9:49

I understand the problem here - but can't find any example how to do it right. I nearly put 'a on every position possible :D

Edit

It was mentioned that I should not put the array as reference into my struct - how should it look to be right?

halfer
  • 19,824
  • 17
  • 99
  • 186
xetra11
  • 7,671
  • 14
  • 84
  • 159

0 Answers0