(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
}

相关推荐
盒马盒马1 天前
Rust:迭代器
开发语言·后端·rust
Source.Liu2 天前
【Iced】stream.rs文件
rust·iced
Kapaseker2 天前
精通 Rust 宏 — 包装新类型
rust
飞函安全2 天前
Vite 8.0:Rust.bundle,性能提升10-30倍
开发语言·人工智能·rust
奋斗中的小猩猩2 天前
OpenClaw不安全,Rust写的ZeroClaw给出满意答案
安全·rust·openclaw·小龙虾
海奥华22 天前
Rust初步学习
开发语言·学习·rust
VermouthSp2 天前
上下文切换
linux·rust
小杍随笔3 天前
【Rust 1.94.0 正式发布:数组窗口、Cargo 配置模块化、TOML 1.1 全面升级|开发者必看】
开发语言·后端·rust
敬业小码哥3 天前
记一次:clion使用rust插件配置环境并开发
学习·rust
NGINX开源社区4 天前
NGINX 引入对 ACME 协议的原生支持
nginx·rust