Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use mutable member Vec?

Tags:

rust

lifetime

How to properly create a member Vec? What am I missing here?

struct PG {
    names: &mut Vec<String>,
}

impl PG {
    fn new() -> PG {
        PG { names: Vec::new() }
    }

    fn push(&self, s: String) {
        self.names.push(s);
    }
}

fn main() {
    let pg = PG::new();
    pg.push("John".to_string());
}

If I compile this code, I get:

error[E0106]: missing lifetime specifier
 --> src/main.rs:2:12
  |
2 |     names: &mut Vec<String>,
  |            ^ expected lifetime parameter

If I change the type of names to &'static mut Vec<String>, I get:

error[E0308]: mismatched types
 --> src/main.rs:7:21
  |
7 |         PG { names: Vec::new() }
  |                     ^^^^^^^^^^
  |                     |
  |                     expected mutable reference, found struct `std::vec::Vec`
  |                     help: consider mutably borrowing here: `&mut Vec::new()`
  |
  = note: expected type `&'static mut std::vec::Vec<std::string::String>`
             found type `std::vec::Vec<_>`

I know I can use parameterized lifetimes, but for some other reason I have to use static.

like image 322
Paulo Lieuthier Avatar asked Nov 05 '25 16:11

Paulo Lieuthier


1 Answers

You don't need any lifetimes or references here:

struct PG {
    names: Vec<String>,
}

impl PG {
    fn new() -> PG {
        PG { names: Vec::new() }
    }

    fn push(&mut self, s: String) {
        self.names.push(s);
    }
}

fn main() {
    let mut pg = PG::new();
    pg.push("John".to_string());
}

Your PG struct owns the vector - not a reference to it. This does require that you have a mutable self for the push method (because you are changing PG!). You also have to make the pg variable mutable.

like image 192
Shepmaster Avatar answered Nov 08 '25 09:11

Shepmaster