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

相关推荐
不爱学英文的码字机器14 小时前
[鸿蒙PC命令行移植适配]移植rust三方库bottom到鸿蒙PC的完整实践
华为·rust·harmonyos
W_LuYi18516 小时前
Tauri + Rust + Vue 3 打造极速轻量桌面应用
java·开发语言·vue.js·rust
星栈17 小时前
Makepad 界面怎么做得更像产品,而不是示例
前端·rust
特立独行的猫a17 小时前
MQTT Client的Tauri应用移植到 OpenHarmony 鸿蒙 PC/ARM64 实践记录
mqtt·华为·rust·harmonyos·tauri·移植·鸿蒙pc
techdashen17 小时前
深入理解 Rust Futures:从零开始,一头扎到底
开发语言·后端·rust
fox_lht18 小时前
GPUI 框架完整学习教程
学习·rust·gpui
好家伙VCC18 小时前
Rust+Bioinfo:80ms极速SNP注释引擎
java·开发语言·算法·rust
吴佳浩1 天前
AI Infra 的真相:Go 没输,rust也不是取代
后端·rust·go
mit6.8242 天前
并发协调的代价
rust
不爱学英文的码字机器2 天前
[鸿蒙PC命令行移植适配]移植rust三方库sd到鸿蒙PC的完整实践
华为·rust·harmonyos