First steps with Rust here. I searched for an answer but couldn't find anything that worked with the latest version.
struct PG
{
names: &mut Vec<String> // line 12
}
impl PG
{
fn new() -> PG
{
PG { names: Vec::new() } // line 19
}
fn push(&self, s: String)
{
self.names.push(s);
}
}
fn main()
{
let pg = PG::new();
pg.push("John".to_string());
}
If I compile the code above, I get:
src/main.rs:12:12: 12:28 error: missing lifetime specifier [E0106]
src/main.rs:12 names: &mut Vec<String>
^~~~~~~~~~~~~~~~
If I change the type of names
to &'static mut Vec<String>
, I get:
src/main.rs:19:21: 19:31 error: mismatched types:
expected `&'static mut collections::vec::Vec<collections::string::String>`,
found `collections::vec::Vec<_>`
(expected &-ptr,
found struct `collections::vec::Vec`) [E0308]
I know I can use parameterized lifetimes, but for some other reason I have to use static
. How to properly create a member Vec? What am I missing here? Thank you very much.
You don't need any lifetimes or references here:
Your
PG
struct owns the vector - not a reference to it. This does require that you have a mutableself
for thepush
method (because you are changingPG
!). You also have to make thepg
variable mutable.