如何使用可变成员Vec? [英] How to use mutable member Vec?

查看:66
本文介绍了如何使用可变成员Vec?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何正确创建成员Vec?我在这里想念什么?

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

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

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

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

I know I can use parameterized lifetimes, but for some other reason I have to use static.

推荐答案

您在这里不需要任何生存期或引用:

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

您的PG结构体拥有向量-而不是对其的引用.这确实要求您对push方法具有可变的self(因为您正在更改PG!).您还必须使pg变量可变.

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.

这篇关于如何使用可变成员Vec?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆