Start learning free

LESSON 116 OF 679 · ARRAYS I

Insert and Remove at a Position in Rust

Lesson

TL ; DR:

insert(i, x) puts x at index i. Use remove(i) to take out the item at index i. The other items move to make room or to close the gap.


let mut colors = vec!["red", "green", "blue"];

colors.insert(1, "pink");
// colors is now ["red", "pink", "green", "blue"]

colors.remove(0);
// colors is now ["pink", "green", "blue"]


Full lesson:

push adds an item at the end, and pop takes the last one away. For any other position, a Vec has insert and remove.

insert(i, x) puts x at index i. The items from index i on move one place to the right:

let mut pets = vec!["Rex", "Milo"];

pets.insert(0, "Luna");
// pets is now ["Luna", "Rex", "Milo"]

remove(i) takes out the item at index i. The items after it move one place to the left. It also returns the item:

let first = pets.remove(0);
// first is "Luna", and pets is now ["Rex", "Milo"]

Both change the Vec, so declare it with let mut.

Watch the indexes. After an insert or a removal, the items behind that spot have new indexes.

An index past the end makes the program panic. One exception: insert accepts the length itself and adds the item at the end.


Your task

pets holds the pets waiting at the vet, in order.

Bella has an appointment, so she goes second, at index 1. Then Milo goes home. Take him out of the line.

The code below prints how many pets wait once Bella is in. At the end, it prints the pets left.

Expected output:

4
Rex Bella Luna
STEP 1 OF 2
    Ctrl + Enter to check