如何使用可变成员Vec?

问题描述 投票:2回答:1

如何正确创建成员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

rust lifetime
1个回答
6
投票

您在这里不需要任何生存期或参考:

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结构拥有向量-不是对其的引用。这确实要求您对self方法具有可变的push(因为您正在更改PG!)。您还必须使pg变量可变。

© www.soinside.com 2019 - 2024. All rights reserved.