Accessing Slice Elements
Part of the Fundamentals section of Coddy's GO journey — lesson 78 of 109.
Accessing slice elements works just like arrays, using square brackets with an index position (starting from 0).
Create a slice of fruits:
fruits := []string{"Apple", "Banana", "Cherry"}
fmt.Println(fruits[0]) // First element
fmt.Println(fruits[1]) // Second element
fmt.Println(fruits[2]) // Third elementThis displays:
Apple
Banana
CherryYou can also modify elements by assigning new values:
fruits[1] = "Blueberry"
fmt.Println(fruits)Result:
[Apple Blueberry Cherry]Challenge
BeginnerIn this challenge, you'll practice accessing elements from a slice in Go.
We've created a slice of fruits for you. Your task is to access specific elements from this slice and print them.
Try it yourself
package main
import "fmt"
func main() {
// A slice of fruits
fruits := []string{"apple", "banana", "cherry", "date", "elderberry"}
// TODO: Access the first fruit (index 0) and store it in a variable called firstFruit
// TODO: Access the third fruit (index 2) and store it in a variable called thirdFruit
// Print the results
fmt.Println("The first fruit is:", firstFruit)
fmt.Println("The third fruit is:", thirdFruit)
}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