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

相关推荐
咚为7 小时前
Rust 经典面试题255道
开发语言·面试·rust
@atweiwei8 小时前
用 Rust 构建 LLM 应用的高性能框架
开发语言·后端·ai·rust·langchain·llm
chrislearn11 小时前
Salvo 为什么不采用宏式路由
rust
Amos_Web1 天前
Solana开发(1)- 核心概念扫盲篇&&扫雷篇
前端·rust·区块链
golang学习记1 天前
VS Code官宣:全面支持Rust!
开发语言·vscode·后端·rust
叹一曲当时只道是寻常1 天前
Tauri v2 + Rust 实现 MCP Inspector 桌面应用:进程管理、Token 捕获与跨平台踩坑全记录
开发语言·后端·rust
怪我冷i2 天前
Rust错误处理之unwrap
rust·cloudflare·unwrap
楚国的小隐士3 天前
为什么说Rust是对自闭症谱系人士友好的编程语言?
java·rust·编程·对比·自闭症·自闭症谱系障碍·神经多样性
Tomhex3 天前
Rust智能指针使用指南
rust
AI自动化工坊4 天前
Claw Code技术深度解析:Python+Rust混合架构的设计与实现
开发语言·人工智能·python·ai·架构·rust·开源