You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Go provides three essential data structures beyond basic types: slices (dynamic arrays), maps (hash tables), and pointers (memory addresses). Understanding these is crucial for writing effective Go code.
Arrays in Go have a fixed size determined at compile time:
var a [5]int // [0, 0, 0, 0, 0]
b := [3]string{"a", "b", "c"} // [a, b, c]
c := [...]int{1, 2, 3, 4} // size inferred: [1, 2, 3, 4]
Arrays are rarely used directly in Go because their size is part of the type — [3]int and [5]int are different types. Use slices instead.
A slice is a dynamically-sized, flexible view into an underlying array. Slices are Go's most commonly used data structure.
// Slice literal
nums := []int{1, 2, 3, 4, 5}
// make(type, length, capacity)
s := make([]int, 5) // len=5, cap=5, all zeros
s := make([]int, 0, 10) // len=0, cap=10, empty but pre-allocated
// Nil slice
var s []int // nil, len=0, cap=0
A slice is a three-field struct internally:
| Field | Description |
|---|---|
| Pointer | Points to the first element of the underlying array |
| Length | Number of elements in the slice |
| Capacity | Number of elements in the underlying array (from the slice start) |
s := make([]int, 3, 10)
fmt.Println(len(s)) // 3
fmt.Println(cap(s)) // 10
s := []int{1, 2, 3}
s = append(s, 4) // [1, 2, 3, 4]
s = append(s, 5, 6, 7) // [1, 2, 3, 4, 5, 6, 7]
// Append one slice to another:
other := []int{8, 9}
s = append(s, other...) // [1, 2, 3, 4, 5, 6, 7, 8, 9]
Important:
appendmay allocate a new underlying array if capacity is exceeded. Always uses = append(s, ...).
s := []int{0, 1, 2, 3, 4, 5}
s[1:4] // [1, 2, 3] — from index 1 to 3
s[:3] // [0, 1, 2] — from start to 2
s[2:] // [2, 3, 4, 5] — from index 2 to end
s[:] // [0, 1, 2, 3, 4, 5] — full slice
src := []int{1, 2, 3}
dst := make([]int, len(src))
n := copy(dst, src) // n = 3, dst = [1, 2, 3]
| Operation | Code |
|---|---|
| Create | s := []int{1, 2, 3} |
| Append | s = append(s, 4) |
| Length | len(s) |
| Capacity | cap(s) |
| Slice | s[1:3] |
| Copy | copy(dst, src) |
| Delete element at i | s = append(s[:i], s[i+1:]...) |
| Check if nil | s == nil |
| Check if empty | len(s) == 0 |
| Sort | slices.Sort(s) (Go 1.21+) |
A map is an unordered collection of key-value pairs (a hash table):
// Map literal
ages := map[string]int{
"Alice": 30,
"Bob": 25,
}
// make
m := make(map[string]int)
// Nil map (read-only — writing panics)
var m map[string]int
// Set a value
ages["Charlie"] = 28
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.