如何正确创建成员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());
}
Run Code Online (Sandbox Code Playgroud)
如果我编译此代码,则会得到:
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());
}
Run Code Online (Sandbox Code Playgroud)
如果将的类型更改names为&'static mut Vec<String>,则会得到:
error[E0106]: missing lifetime specifier
--> src/main.rs:2:12
|
2 | names: &mut Vec<String>,
| ^ expected lifetime parameter
Run Code Online (Sandbox Code Playgroud)
我知道我可以使用参数化的生存期,但是由于某些其他原因,我必须使用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());
}
Run Code Online (Sandbox Code Playgroud)
您的PG结构拥有向量-而不是对其的引用。这确实要求您self对该push方法具有可变性(因为您正在更改PG!)。您还必须使pg变量可变。
| 归档时间: |
|
| 查看次数: |
1042 次 |
| 最近记录: |