How to use mutable member Vec?

2019-08-11 20:09发布

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.

标签: rust lifetime
1条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-08-11 20:46

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.

查看更多
登录 后发表回答