向量vector初始化
初始化 vector 内部数据的方法如下:
rust
fn array_and_vec() -> ([i32; 4], Vec<i32>) {
let a = [10, 20, 30, 40]; // Array
// TODO: Create a vector called `v` which contains the exact same elements as in the array `a`.
// Use the vector macro.
// let v = ???;
let v = vec![10, 20, 30, 40]; // Vector
(a, v)
}
向量vector push 操作
对 input 数组进行迭代,每个元素乘以2然后推入 output 向量
rust
fn vec_loop(input: &[i32]) -> Vec<i32> {
let mut output = Vec::new();
for element in input {
// TODO: Multiply each element in the `input` slice by 2 and push it to
// the `output` vector.
output.push(element * 2);
}
output
}
iter + map + collect 转数组为矢量
rust
fn vec_map_example(input: &[i32]) -> Vec<i32> {
// An example of collecting a vector after mapping.
// We map each element of the `input` slice to its value plus 1.
// If the input is `[1, 2, 3]`, the output is `[2, 3, 4]`.
input.iter().map(|element| element + 1).collect()
}
fn vec_map(input: &[i32]) -> Vec<i32> {
// TODO: Here, we also want to multiply each element in the `input` slice
// by 2, but with iterator mapping instead of manually pushing into an empty
// vector.
// See the example in the function `vec_map_example` above.
input
.iter()
.map(|element| {
// ???
element * 2
})
.collect()
}
可变向量
如果要往向量里加东西,要加 mut 关键字
rust
fn fill_vec(vec: Vec<i32>) -> Vec<i32> {
let mut vec = vec;
// ^^^ added
vec.push(88);
vec
}