0
0
Goprogramming~20 mins

Slice and array relationship in Go - Mini Project: Build & Apply

Choose your learning style9 modes available
Slice and array relationship
📖 Scenario: Imagine you have a list of daily temperatures stored in an array. You want to look at a smaller part of this list, like the temperatures for just a few days, without copying the data. This is where slices come in handy in Go.
🎯 Goal: You will create an array of temperatures, then make a slice from it to see how slices and arrays relate. Finally, you will print the slice to see the selected temperatures.
📋 What You'll Learn
Create an array called temps with these exact values: 20, 22, 19, 24, 25, 23, 21
Create a slice called weekendTemps that includes the last three days from the temps array
Print the weekendTemps slice to show the temperatures for the weekend
💡 Why This Matters
🌍 Real World
Slices let you work with parts of data without copying everything, saving memory and time. This is useful in programs that handle large data like sensor readings or logs.
💼 Career
Understanding slices and arrays is essential for Go developers, especially when optimizing performance and memory usage in real-world applications.
Progress0 / 4 steps
1
Create the array of temperatures
Create an array called temps with these exact integer values: 20, 22, 19, 24, 25, 23, 21.
Go
Hint

Use [7]int{...} to create an array with 7 integers.

2
Create a slice from the array
Create a slice called weekendTemps that includes the last three elements from the temps array using slicing syntax.
Go
Hint

Use temps[4:7] to get elements from index 4 up to but not including 7.

3
Print the slice of weekend temperatures
Use fmt.Println to print the weekendTemps slice. Remember to import the fmt package at the top.
Go
Hint

Use fmt.Println(weekendTemps) to print the slice.

4
Modify the slice and observe the array
Change the first element of weekendTemps to 30. Then print both weekendTemps and the original temps array using fmt.Println to see how the array changes.
Go
Hint

Assign weekendTemps[0] = 30 and then print both variables.