Start learning free

LESSON 112 OF 671 · ARRAYS I

Insert and Remove at a Position in Go

Lesson

TL ; DR:

slices.Insert(s, i, x) puts x at index i. Use slices.Delete(s, i, i+1) to take out the item at index i. Both return the new slice, so assign it back.


colors := []string{"red", "green", "blue"}

colors = slices.Insert(colors, 1, "pink")
fmt.Println(colors)   // [red pink green blue]

colors = slices.Delete(colors, 0, 1)
fmt.Println(colors)   // [pink green blue]


Full lesson:

append adds an item at the end, and re-slicing takes the last one away. For any other position, Go's slices package has two helpers.

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

pets := []string{"Rex", "Milo"}
pets = slices.Insert(pets, 0, "Luna")
fmt.Println(pets)   // [Luna Rex Milo]

slices.Delete(s, i, j) takes out the items from index i up to, not including, j. So j = i + 1 takes out one item. The items after it move to the left:

pets = slices.Delete(pets, 0, 1)
fmt.Println(pets)   // [Rex Milo]

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

Like append, both return the new slice. Always assign the result back to the variable.

The slices package came with Go 1.21. The lesson's code already imports it for you.


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