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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With