How to use mutable member Vec?

人走茶凉 提交于 2019-12-11 02:07:50

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/29415521/how-to-use-mutable-member-vec

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!