如何使用可变成员 Vec?

How to use mutable member Vec?

如何正确创建会员Vec?我在这里错过了什么?

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());
}

如果我编译这段代码,我得到:

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

如果我将 names 的类型更改为 &'static mut Vec<String>,我得到:

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<_>`

我知道我可以使用参数化生命周期,但由于某些其他原因我必须使用 static

此处不需要任何生命周期或引用:

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());
}

您的 PG 结构 拥有 向量 - 不是对它的引用。这确实需要您为 push 方法设置一个可变的 self(因为您正在更改 PG!)。您还必须使 pg 变量可变。