Start learning free

LESSON 118 OF 679 · ARRAYS I

Slicing a Vec in Rust

Lesson

TL ; DR:

v[i..j].to_vec() is a new Vec with the items from index i up to, not including, j. The original doesn't change.


let letters = vec!["a", "b", "c", "d", "e"];

let middle = letters[1..4].to_vec();
// middle is ["b", "c", "d"]

// letters is still ["a", "b", "c", "d", "e"]


Full lesson:

Sometimes you need only part of a Vec, like the first few items. A range of indexes picks that part.

1..4 is the range from 1 up to, not including, 4. So letters[1..4] has the items at 1, 2 and 3.

Leave out the start to begin at index 0. Leave out the end to go to the very end:

let tail = letters[3..].to_vec();
// tail is ["d", "e"]

On its own, letters[1..4] only borrows those items from letters. Then .to_vec() copies them into a new Vec of its own.

The original Vec stays as it was.

A range past the length makes the program panic. So letters[3..9] stops the program with an error.


Your task

runners holds a race's runners, in the order they finished.

Put the first three in a new Vec named podium. Put everyone else, from index 3 to the end, in one named rest.

The code below prints both, then the length of runners.

Expected output:

Ana Ben Cleo
Dan Eve
5
STEP 1 OF 2
    Ctrl + Enter to check