📖 Scenario: You are working with a list of daily temperatures recorded over a week. You want to extract specific parts of this data to analyze trends.
🎯 Goal: Learn how to create and use slices in Go to extract parts of a list.
📋 What You'll Learn
Create a slice with exact temperature values
Create a variable for the slice start index
Use slicing syntax to extract a sub-slice
Print the extracted sub-slice
💡 Why This Matters
🌍 Real World
Slicing is useful when working with parts of data like daily temperatures, sales figures, or user inputs.
💼 Career
Understanding slicing helps in data processing, filtering, and efficient memory use in Go programming jobs.
Progress0 / 4 steps
1
Create the initial slice
Create a slice called temperatures with these exact values: 20, 22, 19, 24, 25, 23, 21
Go
Hint
Use []int{} to create a slice with the given numbers.
2
Set the start index for slicing
Create an integer variable called start and set it to 2
Go
Hint
Use start := 2 to create the variable.
3
Extract a sub-slice using slicing
Create a new slice called weekendTemps that contains the elements from temperatures starting at index start up to index 5 (not including 5) using slicing syntax
Go
Hint
Use sliceName := originalSlice[start:end] to get a sub-slice.
4
Print the extracted sub-slice
Use fmt.Println to print the weekendTemps slice
Go
Hint
Use fmt.Println(weekendTemps) to display the slice.
Practice
(1/5)
1. In Go, what does the slice expression arr[2:5] do?
easy
A. Extracts elements from index 2 up to and including index 5
B. Extracts elements from index 2 up to but not including index 5
C. Extracts elements from index 3 to 5
D. Extracts elements from index 0 to 5
Solution
Step 1: Understand slice indexing in Go
Go slices include the start index but exclude the end index.
Step 2: Apply to arr[2:5]
This means elements at indexes 2, 3, and 4 are included, but not index 5.
Final Answer:
Extracts elements from index 2 up to but not including index 5 -> Option B
Quick Check:
Slice = arr[2:5] includes indexes 2,3,4 [OK]
Hint: Remember: start included, end excluded in slices [OK]
Common Mistakes:
Including the end index element
Confusing start and end indexes
Thinking slice includes elements before start
2. Which of the following is the correct syntax to slice a Go slice arr from the beginning up to index 4 (excluding 4), omitting the start index?
easy
A. arr[:4]
B. arr[0:4]
C. arr[1:4]
D. arr[4:]
Solution
Step 1: Recall slice syntax for start omitted
Omitting the start index means slicing from the beginning (index 0).
Step 2: Check the options
arr[:4] omits the start index (defaults to 0), slicing up to but excluding index 4. arr[0:4] explicitly includes the start index.
Final Answer:
arr[:4] -> Option A
Quick Check:
Start omitted means from 0 [OK]
Hint: Omit start to slice from beginning: arr[:end] [OK]