Vectors

vecs1.rs

fn array_and_vec() -> ([i32; 4], Vec<i32>) {
    let a = [10, 20, 30, 40]; // Array

    // 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];
    (a, v)
}

fn main() {
    // You can optionally experiment here.
}

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

    #[test]
    fn test_array_and_vec_similarity() {
        let (a, v) = array_and_vec();
        assert_eq!(a, *v);
    }
}
  • Rust conveniently provides the vec! macro, which will create a new vector that holds the values you give it.

  • You can specify the vector types the type within angle brackets like Vec<i32>.

  • More often, you’ll create a vector with initial values and Rust will infer the type of value you want to store, so you rarely need to do this type annotation.

  • In this exercise we just need to init new vector using vec! macro.

vecs2.rs

  • In this exercise we have 2 task:

  • First is to iterate through a collection manually using for and multiply each element with 2.

  • Second is to iterate through a collection using iterators and multiply each element with 2.

Last updated