Learn
So far we have covered what arrays and slices are, and how to work with them at a basic level. However, a big aspect of working with slices are that we can add elements and the slice will resize automatically. But how do we add to a slice?
Go provides us with a function, append
that handles all of the logic of adding to and resizing a slice:
books := []string{"Tom Sawyer", "Of Mice and Men"} books = append(books, "Frankenstein") books = append(books, "Dracula") fmt.Println(books) // [Tom Sawyer Of Mice and Men Frankenstein Dracula]
Being able to add new elements to a slice is very important. Especially when data comes in over time that we cannot predict.
Let’s practice appending elements in a Go program!
Instructions
1.
As mentioned before, we need to add some new tutors to our tutoring center.
Can you use the append
function to add Josh
to the list?
2.
Print the slice of tutors after having added Josh
.
Take this course for free
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.