(done) 速通 rustlings(11) 向量vector及其操作

向量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
}

相关推荐
花褪残红青杏小15 分钟前
Rust图像处理第20节-PCA 主成分分析:把图片压缩到 3 个数字
rust·webassembly·图形学
脱胎换骨-军哥8 小时前
C++/Rust无缝互操作:混合系统新常态
开发语言·c++·rust
songroom8 小时前
Kimi K3:Rust封装XTP接口详细教程实践
开发语言·后端·rust
独孤留白15 小时前
从C到Rust:Trait From Into 类型转换
rust
doiito15 小时前
【RUST AI】把 TTS 搬进浏览器:kokoroi-rs 的 WASM 实践
ai·rust·架构设计
jinshw15 小时前
自己实现GIS配图软件(一)
rust·开源·gis
程序员爱钓鱼16 小时前
Rust 元组 Tuple 详解:组合不同类型的数据
前端·后端·rust
humbinal2 天前
同时支持 gui & cli 的 parquet 文件查看工具,高性能小清新!
hive·python·rust·spark·开源·github·parquet
belowfrog2 天前
Rust 的 Deref 到底为啥这么乱呀!
rust
程序员爱钓鱼2 天前
Rust 数组 Array 详解:定义、访问、遍历与切片
后端·rust