📖 Scenario: You are managing a list of daily temperatures recorded in a weather app. Each day, a new temperature is added at the end of the list.
🎯 Goal: Build a program that stores initial temperatures in an array, sets the new temperature to add, inserts it at the end of the array, and then prints the updated array.
📋 What You'll Learn
Create an array called temps with the exact values 20, 22, 19, 23
Create a variable called newTemp and set it to 25
Append newTemp to the end of temps using Go slice append
Print the updated temps array
💡 Why This Matters
🌍 Real World
Weather apps and many other programs often need to add new data points to a list as new information arrives.
💼 Career
Understanding how to add elements to arrays or lists is a fundamental skill for software developers working with data collections.
Progress0 / 4 steps
1
Create the initial array
Create an array called temps with the exact values 20, 22, 19, 23.
DSA Go
Hint
Use temps := []int{20, 22, 19, 23} to create the array.
2
Set the new temperature
Create a variable called newTemp and set it to 25.
DSA Go
Hint
Use newTemp := 25 to create the variable.
3
Append the new temperature
Append newTemp to the end of the temps array using Go's append function.
DSA Go
Hint
Use temps = append(temps, newTemp) to add the new temperature.
4
Print the updated array
Print the updated temps array using fmt.Println.
DSA Go
Hint
Use fmt.Println(temps) to print the array.
Practice
(1/5)
1. What happens when you insert an element at the end of a fixed-size array in Go?
easy
A. You cannot insert because arrays have fixed size
B. The element replaces the first element
C. The element is added and array size increases automatically
D. The array is converted to a slice automatically
Solution
Step 1: Understand Go array size
Arrays in Go have a fixed size defined at declaration and cannot grow.
Step 2: Effect of insertion at end
Since size is fixed, you cannot add new elements beyond the declared size.
Final Answer:
You cannot insert because arrays have fixed size -> Option A
Quick Check:
Fixed size array = no insertion beyond size [OK]
Hint: Arrays have fixed size; no automatic growth on insertion [OK]
Common Mistakes:
Thinking arrays can grow automatically
Confusing arrays with slices
Assuming insertion replaces last element
2. Which of the following is the correct way to append an element 10 to a slice named nums in Go?
easy
A. nums = nums + 10
B. nums.append(10)
C. append(nums, 10)
D. nums = append(nums, 10)
Solution
Step 1: Recall Go slice append syntax
In Go, append returns a new slice with the element added, so assignment is needed.
Step 2: Check each option
nums = append(nums, 10) correctly assigns the result of append to nums. Others are invalid syntax or missing assignment.
Final Answer:
nums = append(nums, 10) -> Option D
Quick Check:
Use append with assignment to add element [OK]
Hint: Always assign append result back to slice variable [OK]