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

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.

主站蜘蛛池模板: 江达县| 微山县| 麻江县| 富川| 丰顺县| 天峨县| 安远县| 阜新市| 探索| 电白县| 博客| 南漳县| 吉隆县| 连云港市| 白河县| 大庆市| 徐水县| 安仁县| 静宁县| 孟连| 高清| 当涂县| 新田县| 泰安市| 庆元县| 南安市| 华安县| 榆树市| 阿荣旗| 宝坻区| 和田县| 巴马| 丰县| 龙口市| 嘉兴市| 沙河市| 安顺市| 黄冈市| 新郑市| 舒城县| 渝中区|