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
Beginnerappend() 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)
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Comparison & Logical Operators
Comparison Operators - Part 1Comparison Operators - Part 2Logical AND OperatorLogical OR OperatorLogical NOT OperatorOperator Precedence BasicsRecap - Making Comparisons7Control Flow: Loops
What The `for` Loop ExplainedFor Loop - BasicFor Loop - Condition OnlyThe `break` KeywordThe `continue` KeywordNested LoopsRecap - Repeating Actions2Variables and Basic Data Types
What is a variableType Inference with `:=`Integers (int)Floating-Point NumbersBooleansStringsZero ValuesConstantsNaming ConventionsRecap - Variables and Types5Basic Input/Output
Formatted OutputFormat VerbsPrinting TypesGetting Basic User InputRecap - Input and Output8Functions
Understanding FunctionsDeclaring a FunctionCalling FunctionsFunction ParametersReturning a Single ValueReturning Multiple ValuesNamed Return ValuesFunction Scope BasicsRecap - Creating Reusable Code3Basic Operators
Arithmetic OperatorsDivision OperatorThe Modulo OperatorAssignment OperatorAugmented Assignment OperatorsIncrement and DecrementRecap - Calculations6Control Flow: Conditionals
The `if` StatementThe `else` KeywordThe `else if` KeywordVariable Shadowing in `if`Initializing VariablesThe `switch` StatementSwitch with ExpressionsSwitch without ExpressionThe `fallthrough` KeywordRecap - Making Decisions