2015-04-02 68 views
1

这里是Rust的第一步。我搜索了一个答案,但无法找到与最新版本一起工作的任何内容。如何使用可变成员Vec?

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

如果我编译上面的代码,我得到:

src/main.rs:12:12: 12:28 error: missing lifetime specifier [E0106] 
src/main.rs:12  names: &mut Vec<String> 
          ^~~~~~~~~~~~~~~~ 

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

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] 

我知道我可以使用参数化生活时间,但由于其他原因,我不得不使用static。如何正确创建会员Vec?我在这里错过了什么?非常感谢你。

+1

也许这会帮助你http://stackoverflow.com/questions/36413364/as-i-can-make-the-vector-is-mutable-inside-struct#36720608 – 2016-04-19 15:05:15

回答

3

你不需要任何的寿命或引用在这里:

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变量可变。

+0

太棒了!不过,我仍然感到困惑。 'pg'和'self'需要可变,但'names'不能?我以为我正在改变'名称',而不是'pg'。如果我能找到有关这方面的好材料,我会学习更多。谢谢! – 2015-04-02 15:16:08

+1

@paulolieuthier结构是完全可变的或不可变的。通过让'pg'可变,你可以*调用需要可变自引用的方法。 **'PG'中的每个**字段在该方法中都是可变的,包括'names'。 – Shepmaster 2015-04-02 16:16:17