CodeBlanks Logo Icon CodeBlanks

Index and get

Access vector elements safely with index and get.

Index and get

There are two ways to reach an element. v[i] gives the value directly but panics out of bounds. v.get(i) returns an Option<&T>:

let v = vec![10, 20, 30];
let a = v[1];          // 20
let b = v.get(2);      // Some(&30)
let c = v.get(5);      // None
// let d = v[5];       // panic: index out of bounds

If you are sure the index is valid, use []; in uncertain cases, like an index coming from the user, use get.

First, last and searching

Frequently used read methods also return Option:

let v = vec![4, 8, 15];
println!("{:?} {:?}", v.first(), v.last());   // Some(4) Some(15)
println!("{}", v.contains(&8));               // true
println!("{:?}", v.iter().position(|&x| x == 15));   // Some(2)

get_mut(i) gives a mutable reference: if let Some(x) = v.get_mut(0) { *x += 1; }.

Practice Ways of access

For let v = vec![10, 20, 30];, print the results of v[1], v.get(2) and v.get(5) on one line ({:?} for the Options).

Starter code

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

Sample solution

main.rs
fn main() {
    let v = vec![10, 20, 30];
    println!("{} {:?} {:?}", v[1], v.get(2), v.get(5));
}

Expected output

20 Some(30) None

Questions and answers

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

1 Why doesn't <code>let v = vec![String::from("a")]; let s = v[0];</code> compile?

  • v[0] tries to move the String out of the vector; &v[0] or clone is needed Correct answer
  • Index 0 is invalid
  • String can't be indexed
  • It compiles

Explanation: Moving a non-Copy element out by index is forbidden (E0507). Take a reference or copy it.

2 Safe access

Question
let v = vec![10, 20, 30];
let c = v.____(5);   // None
Answer
let v = vec![10, 20, 30];
let c = v.get(5);   // None

Explanation: get returns None instead of panicking out of bounds.

3 Expression and result (v = [10, 20, 30])

Term Meaning
v[1] 20
v.get(2) Some(30)
v.get(5) None
v[5] Panic

All lessons in Beginner