[英]How can I change the length of a vector in Rust?
Editor's note: This question predates Rust 1.0 and syntax and methods have changed since then.
编者注:这个问题早于Rust 1.0,语法和方法从那时起就发生了变化。 Some answers account for Rust 1.0.
一些答案解释了Rust 1.0。
I have a function which I would like to have modify a vector in place. 我有一个函数,我想修改一个向量。
fn f(v: &mut Vec<int>) {
v = Vec::from_elem(10 as uint, 0i);
}
fn main() {
let mut v: Vec<int> = Vec::new();
f(&mut v);
}
But this fails to compile. 但这无法编译。 Specifically, I would like to resize
v
to contain 10 elements of value zero. 具体来说,我想调整
v
以包含10个零值元素。 What am I doing wrong? 我究竟做错了什么?
Editor's note: This answer predates Rust 1.0 and is no longer necessarily accurate.
编者注:这个答案早于Rust 1.0,不再一定准确。 Other answers still contain valuable information.
其他答案仍包含有价值的信息。
You're looking for the grow
method. 你正在寻找
grow
方法。
let mut vec = vec![1i,2,3];
vec.grow(4, &10);
println!("{}", vec);
Or a combination of grow
and clear
. 或者是
grow
和clear
的结合。
You can browse the docs here: http://static.rust-lang.org/doc/master/std/vec/struct.Vec.html 您可以在此处浏览文档: http : //static.rust-lang.org/doc/master/std/vec/struct.Vec.html
Use the clear
and resize
methods. 使用
clear
和resize
方法。 (This seems to be the right answer as of Rust 1.0 and 1.5, respectively.) (这似乎是Rust 1.0和1.5的正确答案。)
fn f(v: &mut Vec<u32>) {
// Remove all values in the vector
v.clear();
// Fill the vector with 10 zeros
v.resize(10, 0);
}
fn main() {
let mut v: Vec<u32> = Vec::new();
f(&mut v);
assert!(v == [0,0,0,0,0,0,0,0,0,0]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.