Skip to content
On this page

vecs1: exercises/vecs/vecs1.rs

题目

rust
// vecs1.rs
//
// Your task is to create a `Vec` which holds the exact same elements as in the
// array `a`.
//
// Make me compile and pass the test!
//
// Execute `rustlings hint vecs1` or use the `hint` watch subcommand for a hint.

// I AM NOT DONE

fn array_and_vec() -> ([i32; 4], Vec<i32>) {
    let a = [10, 20, 30, 40]; // a plain array
    let v = // TODO: declare your vector here with the macro for vectors

    (a, v)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_array_and_vec_similarity() {
        let (a, v) = array_and_vec();
        assert_eq!(a, v[..]);
    }
}

您的任务是创建一个Vec,它包含与数组a中完全相同的元素。

题目解析

在Rust中,有两种定义Vector的方法:

  • 一种方案是使用Vec::new()函数创建一个Vec,并用push()方法填充它。
  • 第二种是使用vec![]宏在方括号内定义您的元素。

如果使用第一种,因为要push元素,所以必须声明为可变的,但题目中let v =是不可变的,所以我们使用第二种方式:

rust
fn array_and_vec() -> ([i32; 4], Vec<i32>) {
    let a = [10, 20, 30, 40]; // a plain array
    let v = // TODO: declare your vector here with the macro for vectors 
    let v = vec![10, 20, 30, 40]; 

    (a, v)
}

笔记

  • vector 允许我们在一个单独的数据结构中储存多于一个的值,它在内存中彼此相邻地排列所有的值。
  • vector 只能储存相同类型的值。
  • 在Rust中,有两种定义Vector的方法:
    • 一种方案是使用Vec::new()函数创建一个Vec,并用push()方法填充它。
    • 第二种是使用vec![]宏在方括号内定义您的元素。

参考资料

Powered by VitePress