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

相关推荐
iuyup8 小时前
深度解析 OpenHuman:开源个人 AI 超级智能的 Memory 架构设计
人工智能·rust
techdashen14 小时前
Rust 泛型 vs Java 泛型:它们看起来相似,但骨子里截然不同
java·开发语言·rust
codealy14 小时前
Rust 核心理论与内存安全(二)
安全·rust
Rust研习社14 小时前
告别环境混乱!使用 mise 管理你的开发环境
前端·后端·rust
小杍随笔15 小时前
【Tauri 2.x 自定义 WebView2 用户数据目录完全指南】
架构·rust
樱桃花下的小猫16 小时前
Rust 服务器存档管理 & 地图配置指南
服务器·rust·云鸢互联·零门槛一键开服·腐蚀rust服务器·腐蚀rust稳定低延迟联机·腐蚀rust服务器一键开服
红尘散仙1 天前
一个 `#[uniffi::export]`,把 Rust 接进 React Native
前端·后端·rust
红尘散仙1 天前
一行 `#[specta::specta]`,让 Tauri IPC 有类型
前端·后端·rust
codealy2 天前
Rust 核心理论与内存安全(一)
后端·安全·rust