Basic concepts
In Go, there are three main container types for storing and manipulating collection data:Array、SliceandMap (Map). Here are their detailed descriptions and comparisons:
1. Array
definition:
The array is havingFixed lengthcontainers that store elements of the same type. The length is determined at the time of declaration and is immutable.
Features:
- Value Type: The entire array will be copied when assigning or passing arguments.
- Memory is continuously allocated and accessed quickly.
Declaration and Initialization:
// Declare an integer array of length 3, and the default initialization is zero valuevar arr1 [3]int // Declare and initializearr2 := [3]int{1, 2, 3} // Automatic length inferencearr3 := [...]int{4, 5, 6}
Use scenarios:
Suitable for situations where fixed size and memory sensitive (such as underlying algorithm optimization), but it is rarely used directly in daily development.
2. Slice
definition:
Slices are based on arraysDynamic lengthAbstract, providing more flexible containers. The slice itself is a reference type, and the underlying layer points to an array.
Features:
-
Dynamic expansion: Length can grow dynamically (by
append
function). - Quote semantics: Pass pointers when assigning values or passing parameters, multiple slices may share the underlying array.
Declaration and Initialization:
// Declare slices directly (nil slices)var s1 []int // Create slices through arrayarr := [5]int{1, 2, 3, 4, 5} s2 := arr[1:3] // Contains elements [2, 3] // Create slices with makes3 := make([]int, 3, 5) // Length 3, capacity 5 // Direct initializations4 := []int{1, 2, 3}
Common operations:
s := []int{1, 2} s = append(s, 3) // Append element → [1, 2, 3]sub := s[1:] // Intercept sub-slice → [2, 3]
Use scenarios:
The default choice for most collection operations (such as dynamic listing, data stream processing).
3. Map (Map)
definition:
The map isKey-ValueThe unordered set of the keys must be hashable (such asint
、string
)。
Features:
- Dynamic expansion: Automatically grow to accommodate more key-value pairs.
- Quote semantics: Pass pointer when assigning or passing arguments.
- The key is unique and the value can be repeated.
Declaration and Initialization:
// Declare a map (nil map, cannot be used directly)var m1 map[string]int // Initialize using makem2 := make(map[string]int) // Direct initializationm3 := map[string]int{ "Alice": 25, "Bob": 30, }
Common operations:
m := map[string]int{} m["Charlie"] = 28 // Add or modify key-value pairsage, ok := m["Bob"] // Check whether the key exists (ok is bool)delete(m, "Alice") // Delete key
Use scenarios:
Quick search, deduplication counting, configuration management and other scenarios that require key-value correlation.
Comparative summary
characteristic | Array | Slice | Map (Map) |
---|---|---|---|
length | fixed | Dynamically variable | Dynamically variable |
Type Semantics | Value type (copy the entire data) | Reference type (sharing the underlying array) | Reference type (shared storage) |
Memory allocation | Compile time confirmation | Dynamic allocation at runtime | Dynamic allocation at runtime |
Access methods | Index (0-based) | Index (0-based) | Key |
Main uses | Fixed-size data blocks | Dynamic collection operation | Key-value pairs associated storage |
Things to note
Slice Sharing Low-level Array:
Multiple slices may share the same underlying array, and modifying one slice may affect other slices.
arr := [3]int{1, 2, 3} s1 := arr[:] // s1 = [1,2,3] s2 := s1[1:] // s2 = [2,3] s2[0] = 100 // s1 becomes [1,100,3]
The disorder of the map:
When traversing the map, the order of key-value pairs is not fixed (Go 1.12+ randomizes the traversal order when expanding).
Concurrency security:
Slices and maps need to be locked (or used when reading and writing concurrently.)。
This is the end of this article about the detailed explanation of the data structures of three container types in Go. For more related Go data structure content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!