Menu
Coddy logo textTech

Appending Elements

Part of the Fundamentals section of Coddy's GO journey — lesson 79 of 109.

The append function adds elements to the end of a slice, automatically handling capacity changes.

Create a slice of numbers:

numbers := []int{1, 2, 3}
fmt.Println(numbers)

Append a new element:

numbers = append(numbers, 4)
fmt.Println(numbers)

Result:

[1 2 3]
[1 2 3 4]

You can append multiple elements at once:

numbers = append(numbers, 5, 6, 7)
fmt.Println(numbers)

Result:

[1 2 3 4 5 6 7]
challenge icon

Challenge

Beginner
In this challenge, you'll practice appending elements to a slice in Go. We've created a slice of fruits, and your task is to append two more fruits to it using the append() function.

Cheat sheet

The append function adds elements to the end of a slice, automatically handling capacity changes.

Append a single element:

numbers := []int{1, 2, 3}
numbers = append(numbers, 4)
fmt.Println(numbers) // [1 2 3 4]

Append multiple elements at once:

numbers = append(numbers, 5, 6, 7)
fmt.Println(numbers) // [1 2 3 4 5 6 7]

Try it yourself

package main

import "fmt"

func main() {
	// A slice of fruits
	fruits := []string{"apple", "banana", "orange"}
	
	// TODO: Append "grape" and "kiwi" to the fruits slice
	// Write your code here
	
	// Print the updated slice
	fmt.Println("My fruit collection:", fruits)
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals