Go•Slices & Arrays
Go Slices: append, make, copy, and Slicing Operations
Slices are dynamically-sized views over contiguous underlying arrays, providing the primary sequence abstraction in Go.
Syntax
s := make([]int, length, capacity)
s = append(s, newElement)
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| append | Built-in Function | Appends elements to slice, allocating new backing array if capacity is exceeded. |
| make | Built-in Function | Allocates and initializes slices, maps, or channels. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing Go locally:
package main
import "fmt"
func main() {
// Creating slice with make([]type, len, cap)
numbers := make([]int, 0, 4)
fmt.Printf("Initial: len=%d, cap=%d\n", len(numbers), cap(numbers))
// Dynamically appending
numbers = append(numbers, 10, 20, 30)
fmt.Printf("After 3 adds: len=%d, cap=%d, values=%v\n", len(numbers), cap(numbers), numbers)
// Slicing operations
sub := numbers[1:3] // index 1 to 2 inclusive
fmt.Printf("Sub-slice [1:3]: %v\n", sub)
}Expected Output:
Initial: len=0, cap=4 After 3 adds: len=3, cap=4, values=[10 20 30] Sub-slice [1:3]: [20 30]
How It Works: Step-by-Step
- Lines 7-8: make([]int, 0, 4) pre-allocates slice with capacity 4.
- Lines 11-12: append adds elements and updates length.
- Lines 15-16: numbers[1:3] creates a sub-slice view.
Key Concepts
- A slice is a 3-word struct: pointer to backing array, length, and capacity.
- When append exceeds capacity, Go automatically allocates a new larger backing array and copies elements.
- Sub-slices share the same underlying backing array.
Common Mistake: Forgetting to reassign the result of append()
append returns a new slice header; failing to reassign s = append(s, val) causes compile or logic bugs.
❌ Incorrect
append(numbers, 40) // Compile Error: append result not used
✅ Correct
numbers = append(numbers, 40)
Related Go Tutorials & Compiler
Go Maps: Key-Value Hash Tables and the Comma-Ok Idiom
Store and retrieve key-value pairs using Go maps with the comma-ok idiom.
Go Structs: Fields, Tags, and Custom Types
Define structured records in Go with typed fields and field tags.
Go Strings, Runes, and the strings Package
Understand UTF-8 encoded strings, runes (Unicode code points), and strings package functions.
Go Online Compiler
Open in Compilra IDE
Run and test Go on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.