Go:Go Slices: append, make, copy, and Slicing Operations
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:

ParameterTypeDescription
appendBuilt-in FunctionAppends elements to slice, allocating new backing array if capacity is exceeded.
makeBuilt-in FunctionAllocates and initializes slices, maps, or channels.

Ready-to-Run Code Example

Executable in Compilra

Run 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

Run and test Go on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Go Online Compiler