# Go Collection Types
## Summary
Go offers several built-in and standard library collection types beyond the primary arrays, slices, and maps. Each collection serves different use cases with their own strengths and trade-offs. Understanding these options helps in choosing the right data structure for specific programming needs.
## Details
### Built-in Collection Types
#### 1. Arrays
Fixed-size collections with compile-time size verification.
```go
// Declaration and initialization
var numbers [5]int = [5]int{1, 2, 3, 4, 5}
primes := [5]int{2, 3, 5, 7, 11}
fibonacci := [...]int{1, 1, 2, 3, 5, 8, 13}
```
**Key characteristics:**
- Fixed size is part of the type signature
- Zero-indexed
- Elements initialized to zero values
- Pass by value (copying the entire array)
#### 2. Slices
Dynamic, flexible views into arrays with automatic memory management.
```go
// Creating slices
numbers := []int{1, 2, 3, 4, 5}
scores := make([]int, 5) // Length 5, capacity 5
scores2 := make([]int, 3, 5) // Length 3, capacity 5
// Slicing operations
slice1 := numbers[1:4] // [2, 3, 4]
```
**Key characteristics:**
- Reference type (points to underlying array)
- Dynamic size with `append`
- Three components: pointer, length, capacity
- Shares underlying array memory
#### 3. Maps
Hash table implementation for key-value associations.
```go
// Creation and usage
ages := map[string]int{
"Alice": 30,
"Bob": 25,
}
// Operations
ages["Dave"] = 22
age, exists := ages["Eve"]
delete(ages, "Bob")
```
**Key characteristics:**
- Unordered collection
- Dynamic size
- Reference type
- Keys must be comparable
- Zero value is nil
#### 4. Strings
Immutable byte sequences with UTF-8 encoding.
```go
text := "Hello, 世界"
fmt.Println(len(text)) // 13 (bytes, not runes)
fmt.Println(text[0]) // 72 (byte value for 'H')
fmt.Println([]rune(text)) // Convert to rune slice
```
**Key characteristics:**
- Immutable
- UTF-8 encoded
- Can be indexed as bytes
- Need conversion to rune for proper Unicode handling
#### 5. Channels
Typed conduits for communication between goroutines.
```go
// Creating channels
ch := make(chan int) // Unbuffered
bufferedCh := make(chan int, 5) // Buffered with capacity 5
// Send and receive
go func() { ch <- 42 }() // Send
value := <-ch // Receive
```
**Key characteristics:**
- Synchronization primitive
- Can be buffered or unbuffered
- Support closing to signal completion
- Used for goroutine communication
### Standard Library Collections
#### 1. List (container/list)
Doubly linked list implementation.
```go
import "container/list"
l := list.New()
l.PushBack("first")
front := l.PushFront("start")
l.InsertAfter("after", front)
for e := l.Front(); e != nil; e = e.Next() {
fmt.Println(e.Value)
}
```
**Use for:**
- Frequent insertions/removals at any position
- No random access requirements
- Need for stable pointers to elements
#### 2. Ring (container/ring)
Circular list implementation.
```go
import "container/ring"
r := ring.New(5)
for i := 0; i < r.Len(); i++ {
r.Value = i
r = r.Next()
}
r.Do(func(v interface{}) {
fmt.Println(v)
})
```
**Use for:**
- Circular buffer patterns
- Round-robin scheduling
- Fixed-size collections with wrap-around
#### 3. Heap (container/heap)
Priority queue implementation.
```go
import "container/heap"
// Implementing heap.Interface
type IntHeap []int
func (h IntHeap) Len() int { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *IntHeap) Push(x interface{}) { *h = append(*h, x.(int)) }
func (h *IntHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[0 : n-1]
return x
}
// Using the heap
h := &IntHeap{2, 1, 5}
heap.Init(h)
heap.Push(h, 3)
fmt.Println(heap.Pop(h)) // 1 (smallest value)
```
**Use for:**
- Priority queues
- Scheduling
- Graph algorithms (Dijkstra, etc.)
- Maintaining sorted elements with efficient insertion
### Common Patterns
#### 1. Set Implementation with Maps
```go
// Creating a set
set := make(map[string]struct{})
// Add elements
set["apple"] = struct{}{}
set["banana"] = struct{}{}
// Check membership
_, exists := set["apple"]
// Delete element
delete(set, "apple")
```
**Key properties:**
- Memory efficient (empty struct takes no space)
- O(1) operations for add/remove/check
- No duplicate values
#### 2. Ordered Map Implementation
```go
type OrderedMap struct {
keys []string
data map[string]interface{}
}
func NewOrderedMap() *OrderedMap {
return &OrderedMap{
keys: make([]string, 0),
data: make(map[string]interface{}),
}
}
func (om *OrderedMap) Set(key string, value interface{}) {
if _, exists := om.data[key]; !exists {
om.keys = append(om.keys, key)
}
om.data[key] = value
}
```
**Use when:**
- Requiring ordered iteration
- Maintaining insertion order
- Need for both fast lookup and ordered traversal
### Selection Guidelines
1. **Use Arrays When:**
- Size is fixed and known at compile time
- Performance is critical
- Want value semantics (full copies)
- Small, fixed-sized collections
2. **Use Slices When:**
- Size may change
- Working with sequences
- Pass by reference needed
- Most general-purpose sequential collection needs
3. **Use Maps When:**
- Key-value association required
- Fast lookups by non-integer keys
- Membership testing
- Removing duplicates
4. **Use Lists When:**
- Frequent insertions/removals at arbitrary positions
- Stable element addresses needed
- No need for indexed access
5. **Use Heap When:**
- Priority queue functionality needed
- Always need smallest/largest element quickly
- Ordered insertion with quick min/max extraction
6. **Use Rings When:**
- Circular buffer semantics required
- Fixed size with overwrites
- Round-robin processing
7. **Use Channels When:**
- Concurrent access needed
- Communication between goroutines
- Synchronization required
## 🔗 Related Resources
- [Go Pointers - When to Use and Notation Guide](/Users/jp/notes/3.Resources/Go%20Pointers%20-%20When%20to%20Use%20and%20Notation%20Guide.md)
- [Functional Options Pattern in Go](/Users/jp/notes/3.Resources/Functional%20Options%20Pattern%20in%20Go.md)
- [Go Logging with slog](/Users/jp/notes/3.Resources/Go%20Logging%20with%20slog.md)
- [Effective Go - Arrays, Slices, and Maps](https://golang.org/doc/effective_go#arrays)
- [Go Container Package Documentation](https://pkg.go.dev/container)
- [Go by Example: Collection Types](https://gobyexample.com/)