这里是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?我在这里错过了什么?非常感谢你。
也许这会帮助你http://stackoverflow.com/questions/36413364/as-i-can-make-the-vector-is-mutable-inside-struct#36720608 – 2016-04-19 15:05:15