Arrays:
Array in Go is a fixed length in size, used to store multiple values of same data type in a single variable. It can’t be resized.
Declare an Array:
There are two ways to declare
- With the var keyword
- var array_name = [length]datatype{values}
or
var array_name = [...]datatype{values}
- With the := sign:
- array_name := [length]datatype{values}
or
array_name := [...]datatype{values}
// Various ways to declare arrays
var arr1 [5]int // All zeros: [0, 0, 0, 0, 0]
arr2 := [3]string{"a", "b", "c"} // Literal initialization
arr3 := [...]int{1, 2, 3} // Compiler counts size
arr := [5]int{10, 20, 30, 40, 50}
// Access and modify
arr[0] = 100
value := arr[2]
// Length
len(arr) // Returns 5
// Iteration
for i, v := range arr {
fmt.Printf("Index %d: %d\n", i, v)
}
Dynamic Arrays
Slices are dynamic, flexible views into arrays. They're the most common collection type in Go.
// Creating slices
var s1 []int // Nil slice
s2 := []int{1, 2, 3} // Slice literal
s3 := make([]int, 5) // Length 5, capacity 5
s4 := make([]int, 5, 10) // Length 5, capacity 10
s5 := arr[1:4] // Slicing from array
// Slicing operations
arr := [5]int{1, 2, 3, 4, 5}
slice := arr[1:4] // [2, 3, 4]
slice2 := slice[1:3] // [3, 4] (further slice)
// Full slice expression (capacity control)
slice3 := arr[1:3:4] // length 2, capacity 3
Array vs Slice
| Feature | Array [n]T | Slice []T |
|---|---|---|
| Length | Fixed at compile time | Dynamic at runtime |
| Type identity | Length is part of type | Length NOT part of type |
| Memory allocation | Stack or inline | Heap (usually) |
| Pass to function | Copy (by value) | Reference (header copy) |
| Resizability | ❌ Cannot resize | ✅ Can grow/shrink |
| Append operation | ❌ Not possible | ✅ append() function |
| Nil value | ❌ Cannot be nil | ✅ Can be nil |
| Comparison | ✅ Comparable (==) | ❌ Only comparable to nil |