CodeBlanks Logo Icon CodeBlanks

Vec<T>

Create dynamic arrays with Vec<T>.

Defining a Vec<T>

Vec<T> is a collection that stores values of the same type contiguously and can grow or shrink at runtime. The elements live on the heap; the vector itself (pointer, length, capacity) is on the stack:

let bos: Vec<i32> = Vec::new();   // the type must be given
let sifirlar = vec![0; 4];        // [0, 0, 0, 0]
let sayilar = vec![1, 2, 3];      // type inferred: Vec<i32>

Since an empty vector has no elements, the compiler can't guess the type; either you write it or it's inferred from later use.

Array or vector?

An array ([i32; 3]) has a fixed size and lives on the stack; the size is part of the type. A vector can grow. If the size is known at compile time and won't change, use an array; otherwise a vector:

let aylar = ["Oca", "Şub", "Mar"];      // [&str; 3]
let mut notlar = Vec::new();
notlar.push(85);                         // Vec<i32>

Both convert to a &[T] slice, so functions taking slices work with both.

Practice Create vectors

Create three vectors: an empty Vec<i32> (Vec::new()), vec![0; 4] and vec![1, 2, 3]. Print the empty vector's length and the other two with {:?} on one line.

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
fn main() {
    let bos: Vec<i32> = Vec::new();
    let sifirlar = vec![0; 4];
    let sayilar = vec![1, 2, 3];
    println!("{} {:?} {:?}", bos.len(), sifirlar, sayilar);
}

Expected output

0 [0, 0, 0, 0] [1, 2, 3]

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is <code>vec![7; 3]</code>?

  • [3, 3, 3, 3, 3, 3, 3]
  • [0, 1, 2]
  • [7, 7, 7] Correct answer
  • [7, 3]

Explanation: vec![value; count] produces the given number of copies of the value.

2 Repeated vector

Question
let sifirlar = vec![0____4];   // [0, 0, 0, 0]
Answer
let sifirlar = vec![0;4];   // [0, 0, 0, 0]

Explanation: In the vec![value; count] syntax, the separator is a semicolon.

3 Expression and result

Term Meaning
Vec::<i32>::new() []
vec![0; 4] [0, 0, 0, 0]
vec![1, 2, 3].len() 3
[1, 2, 3] Array, fixed size

All lessons in Beginner