0
0
Goprogramming~10 mins

Slice creation in Go - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Slice creation
Declare slice variable
Allocate underlying array
Set slice length and capacity
Slice ready to use
Access or modify elements
Creating a slice involves declaring it, allocating an underlying array, setting its length and capacity, then using it to access or modify elements.
Execution Sample
Go
package main
import "fmt"
func main() {
  s := make([]int, 3, 5)
  fmt.Println(s)
}
This code creates a slice of integers with length 3 and capacity 5, then prints it.
Execution Table
StepActionSlice LengthSlice CapacityUnderlying Array SizeOutput
1Declare slice variable s000
2Call make([]int, 3, 5)355
3Slice s created with length 3, capacity 5355
4Print slice s355[0 0 0]
💡 Slice s is created with length 3 and capacity 5; printing shows default zero values.
Variable Tracker
VariableStartAfter Step 2After Step 3Final
snilslice with len=3 cap=5slice with len=3 cap=5slice with len=3 cap=5
Key Moments - 2 Insights
Why does the slice print show three zeros instead of five?
Because the slice length is 3, only the first 3 elements are accessible and printed, even though capacity is 5 (see execution_table step 4).
What is the difference between slice length and capacity?
Length is how many elements the slice currently holds (step 3), capacity is the total space allocated in the underlying array (step 2).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 2, what is the capacity of slice s?
A0
B3
C5
Dnil
💡 Hint
Check the 'Slice Capacity' column at step 2 in execution_table.
At which step does the slice s get its length set to 3?
AStep 2
BStep 1
CStep 3
DStep 4
💡 Hint
Look at the 'Slice Length' column in execution_table to see when length changes from 0 to 3.
If we change make([]int, 3, 5) to make([]int, 5, 5), what will be the output at step 4?
A[0 0 0]
B[0 0 0 0 0]
C[]
Dnil
💡 Hint
The output shows elements equal to the slice length; see how length affects output in execution_table step 4.
Concept Snapshot
Slice creation in Go:
- Use make([]Type, length, capacity)
- Length = accessible elements
- Capacity = underlying array size
- Default values are zero
- Printing shows elements up to length
Full Transcript
In Go, creating a slice involves declaring a slice variable and using the make function to allocate an underlying array with a specified length and capacity. The length determines how many elements are accessible and printed, while the capacity is the total allocated space. For example, make([]int, 3, 5) creates a slice with length 3 and capacity 5. When printed, only the first 3 elements show, initialized to zero. Understanding the difference between length and capacity helps manage slices effectively.