CodeBlanks Logo Icon CodeBlanks

Array

Learn fixed-size arrays of type [T; n].

Arrays

An array holds a fixed number of elements of the same type on the stack. Its type is [T; N] and the length is part of the type:

let notlar: [i32; 4] = [70, 85, 90, 55];
let sifirlar = [0; 5];        // [0, 0, 0, 0, 0]
println!("{} {}", notlar[0], notlar.len());

An out-of-range index (e.g. notlar[10]) panics at run time; Rust never touches invalid memory. For safe reading, notlar.get(10) returns an Option.

Iterating an array

Arrays are iterated with for, and iterator methods can be used:

let notlar = [70, 85, 90, 55];
for n in notlar {
    print!("{n} ");
}
let toplam: i32 = notlar.iter().sum();
let en_yuksek = notlar.iter().max().unwrap();
println!("\n{toplam} {en_yuksek}");

For lists whose length changes at run time, Vec<T> is used instead of an array.

Practice Grade statistics

For let notlar = [70, 85, 90, 55];, find the sum with .iter().sum::<i32>() and the highest grade with .iter().max(), and print println!("{} {}", toplam, en_yuksek);.

Starter code

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

Sample solution

main.rs
fn main() {
    let notlar = [70, 85, 90, 55];
    let toplam = notlar.iter().sum::<i32>();
    let en_yuksek = notlar.iter().max().unwrap();
    println!("{} {}", toplam, en_yuksek);
}

Expected output

300 90

Questions and answers

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

1 What does <code>[1, 2, 3].get(5)</code> return?

  • Some(0)
  • None Correct answer
  • A panic
  • 0

Explanation: get reports the bounds check in its result: Some(&value) for a valid index, None otherwise.

2 Array type

Question
let gunler: [&str; ____] = ["Pzt", "Sal", "Çar"];
Answer
let gunler: [&str; 3] = ["Pzt", "Sal", "Çar"];

Explanation: The number in an array type is the element count and must match the value.

3 Expression and result

Term Meaning
[0; 3] [0, 0, 0]
[1, 2, 3].len() 3
[1, 2][5] panic
[1, 2].get(5) None

All lessons in Beginner