0
0
Goprogramming~10 mins

Common slice operations in Go - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Common slice operations
Create slice
Access elements
Modify elements
Append elements
Slice sub-slices
Delete elements (via slicing)
Use slice length and capacity
This flow shows how to create, access, modify, append, slice, delete elements, and check length/capacity of slices in Go.
Execution Sample
Go
package main
import "fmt"
func main() {
  s := []int{1, 2, 3}
  s = append(s, 4)
  fmt.Println(s[1])
}
Creates a slice, appends an element, and prints the second element.
Execution Table
StepActionSlice sOutput
1Create slice s with [1, 2, 3][1 2 3]
2Append 4 to s[1 2 3 4]
3Access s[1][1 2 3 4]2
4End of program[1 2 3 4]2
💡 Program ends after printing element at index 1.
Variable Tracker
VariableStartAfter CreateFinal
snil[1 2 3][1 2 3 4]
Key Moments - 3 Insights
Why does s change after append even though slices are passed by value?
Append returns a new slice header with updated length and capacity, so we assign it back to s as shown in step 2 of execution_table.
What happens if we try to access s[3] before appending?
Accessing s[3] before append would cause a runtime error because the slice length is 3, so index 3 is out of range (see step 1 slice length).
How do we delete an element from a slice?
We create a new slice by combining parts before and after the element using slicing and append, similar to how append works in step 2.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of slice s after step 2?
A[1 2 3]
B[1 2 3 4]
C[2 3 4]
D[1 2 4]
💡 Hint
Check the 'Slice s' column at step 2 in execution_table.
At which step is the element '2' printed?
AStep 3
BStep 1
CStep 2
DStep 4
💡 Hint
Look at the 'Output' column in execution_table for when '2' appears.
If we remove the assignment in step 2 (s = append(s, 4)), what happens to s?
As becomes nil
Bs becomes [1 2 3 4]
Cs remains [1 2 3]
DProgram crashes
💡 Hint
Refer to key_moments about append behavior and variable_tracker for s changes.
Concept Snapshot
Slices in Go:
- Create: s := []int{1,2,3}
- Access: s[0], s[1]
- Append: s = append(s, 4)
- Slice: s[1:3]
- Delete: s = append(s[:i], s[i+1:]...)
- Length: len(s), Capacity: cap(s)
Full Transcript
This visual execution shows common slice operations in Go. We start by creating a slice s with three elements. Then we append a new element 4 to s, which returns a new slice header that we assign back to s. Next, we access the element at index 1, which is 2, and print it. The program ends after printing. The variable tracker shows how s changes from nil to [1 2 3] and finally to [1 2 3 4]. Key moments clarify why append requires assignment, what happens if we access out-of-range indexes, and how to delete elements by slicing and appending. The quiz tests understanding of slice state after append, when output occurs, and the effect of missing assignment after append.