Back to Blog

Arrays & Slices (Append, Make, Copy & Slicing) - Go Tutorial for Beginners #9

Sandy LaneSandy Lane

Video: Arrays & Slices (Append, Make, Copy & Slicing) - Go Tutorial for Beginners #9 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Arrays & Slices in Go: Append, Make, Copy & Slicing

Go provides powerful built-in collection types: fixed-size arrays and dynamic slices. Arrays have a fixed length and value semantics, while slices are more flexible, referencing underlying arrays and supporting dynamic resizing with functions like append and make.

Code

package main

import "fmt"

func main() {
  // Array: fixed size, value type
  var arr [5]int                  // array of 5 integers, initialized to zero
  fruits := [3]string{"apple", "banana", "cherry"}

  fmt.Println("Array arr:", arr)
  fmt.Println("Array fruits:", fruits)

  // Slice: dynamic size, reference type
  nums := []int{10, 20, 30, 40, 50}
  fmt.Println("Original slice nums:", nums)

  // Slicing with colon notation
  fmt.Println("First 3 elements:", nums[:3])  // indices 0,1,2
  fmt.Println("From index 2 to end:", nums[2:]) // indices 2,3,4

  // Append elements to slice
  nums = append(nums, 60, 70)
  fmt.Println("After append:", nums)

  // Append another slice using ... operator
  more := []int{80, 90}
  nums = append(nums, more...)
  fmt.Println("After appending more:", nums)

  // Create slice with make: length 5, capacity 10
  buffer := make([]int, 5, 10)
  fmt.Printf("Buffer slice len=%d cap=%d: %v\n", len(buffer), cap(buffer), buffer)

  // Copy slice to create independent copy
  src := []int{1, 2, 3, 4}
  dst := make([]int, len(src))
  copy(dst, src)
  dst[0] = 100  // modifying dst does not affect src
  fmt.Println("Source slice:", src)
  fmt.Println("Copied slice:", dst)

  // Nil vs empty slice
  var nilSlice []int           // nil slice, no underlying array
  emptySlice := []int{}        // empty slice, zero length but non-nil
  fmt.Println("nilSlice is nil?", nilSlice == nil)
  fmt.Println("emptySlice is nil?", emptySlice == nil)
}

Key Points

  • Arrays have fixed size and are value types, copying the entire array when assigned.
  • Slices are dynamically sized, reference an underlying array, and support slicing with colon notation.
  • The append function adds elements to a slice, growing it as needed.
  • make creates slices with specified length and capacity for efficient memory usage.
  • copy duplicates slice contents into a new slice, enabling independent modifications.
  • Nil slices have no underlying array and compare equal to nil, while empty slices have zero length but are non-nil.