Griffin SC HW 06 - TheEvergreenStateCollege/upper-division-cs-23-24 GitHub Wiki

Chapter 8: Common Collections (Vector,

https://canvas.evergreen.edu/courses/6250/assignments/119632

Vector

  • a collection that stores values of the same type
  • mutable

Creating a Vector:

There are 3 ways to create a vector:


  1. let v: Vec = Vec::new();

In this approach we specify the type of values stored in the vector.
The Vec specifies the type (i32 in the example, but it could be any type).


  1. let v = vec![1, 2, 3];

In this approach we use the vec! macro, and we initialize the vector with values.
The vector can assume that it is an i32 vector because the values are all integers.


  1. let mut v = Vec::new();
    v.push(5);

In this approach we don't specify the type of value stored in the vector.
Why don't we need to specify the value?
A. Rust can infer the type when we push a value to it
-note the mut keyword. It is required to update the vector.

Updating a Vector:

You can use .push() to add values to a vector.

Example:
v.push(5)

v is a vector, and 5 is added to the vector

Referencing a Vector:

There are two ways: indexing and the get method.

Example of indexing:
image

Vector Quiz 1:

image

image

image

Vector Quiz 2:

Strings

image

⚠️ **GitHub.com Fallback** ⚠️