(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 小时前
RUST中的trait是什么?
笔记·rust
Embedded-Xin20 小时前
中间件—zenoh零基础入门
linux·中间件·rust·机器人·自动驾驶·嵌入式
程序员爱钓鱼1 天前
Rust 可变借用详解:&mut T 与安全修改数据
后端·面试·rust
SomeB1oody1 天前
【RustyML入门】2.9. MeanShift
开发语言·后端·机器学习·rust·教程
SomeB1oody2 天前
【RustyML入门】2.10. 主成分分析
开发语言·后端·机器学习·rust·教程
yushikong2 天前
关于rust开发ch32x033f8p6的一些记录
开发语言·后端·rust
程序员爱钓鱼2 天前
Rust Borrow借用详解:不转移所有权访问数据
后端·面试·rust
程序员爱钓鱼2 天前
Rust Copy详解:隐式复制与轻量数据类型
前端·后端·rust
kaixin_learn_qt_ing2 天前
了解Rust/Tauri
rust