官术网_书友最值得收藏!

Vectors

Vectors are like arrays, except that their content or length doesn't need to be known in advance and can grow on demand. They are allocated on the heap. They can be created by either calling the Vec::new constructor or by using the vec![] macro:

// vec.rs

fn main() {
let mut numbers_vec: Vec<u8> = Vec::new();
numbers_vec.push(1);
numbers_vec.push(2);

let mut vec_with_macro = vec![1];
vec_with_macro.push(2);
let _ = vec_with_macro.pop(); // value ignored with `_`

let message = if numbers_vec == vec_with_macro {
"They are equal"
} else {
"Nah! They look different to me"
};

println!("{} {:?} {:?}", message, numbers_vec, vec_with_macro);
}

In the preceding code, we created two vectors, numbers_vec and vec_with_macro, in different ways. We can push elements to our vector using push() method and can remove elements using pop(). There are more methods for you to explore if you go to their documentation page: https://doc.rust-lang.org/std/vec/struct.Vec.html . Vectors can also be iterated using the for loop syntax as they also implement the Iterator trait.

主站蜘蛛池模板: 黎城县| 乐山市| 施甸县| 金川县| 兴仁县| 邢台县| 新余市| 泾源县| 兴城市| 淮安市| 定陶县| 新泰市| 全州县| 梅州市| 靖江市| 颍上县| 淮滨县| 香港 | 桂阳县| 栖霞市| 万州区| 万安县| 威信县| 大宁县| 汤阴县| 临安市| 旬阳县| 密云县| 洛阳市| 乐都县| 江阴市| 万宁市| 巴林左旗| 美姑县| 怀远县| 望奎县| 武功县| 独山县| 云林县| 安宁市| 武陟县|