Comparison#

Nil Behavior#

FeatureSliceMap
Append/WriteAppendable (allocates new array)Panic (assignment to nil map)
ReadSafe (returns zero value if index/key handled)Safe (returns zero value)
LenReturns 0Returns 0

eg.

var s []int
s = append(s, 1) // Safe
var m map[string]int
m["key"] = 1 // Panic

clear() (Go 1.21+)#

The clear builtin behaves differently depending on the type.

  • Slice: Sets all elements to their zero value. The length and capacity remain unchanged.
  • Map: Removes all entries. The length becomes 0.

eg.

s := []int{1, 2, 3}
clear(s)
fmt.Println(s)      // [0 0 0]
fmt.Println(len(s)) // 3
m := map[string]int{"a": 1, "b": 2}
clear(m)
fmt.Println(m)      // map[]
fmt.Println(len(m)) // 0

Struct vs Reference Types (Slice/Map)#

Nilability#

Unlike slices and maps, a struct cannot be nil. Declaring a struct variable without an initializer is equivalent to using an empty literal.

eg.

var nums []int           // nil
data := []int{}          // non-nil

var scores map[int]int   // nil
points := map[int]int{}  // non-nil

type Config struct{}
var cfg Config           // Instance of Config (cannot be nil)
base := Config{}         // Equivalent to above

Initialization with make#

The make built-in function is exclusively used for Slice, Map, and Channel. It cannot be used to initialize structs.

Comparability#

TypeComparable?Note
SliceNoOnly comparable to nil.
MapNoOnly comparable to nil.
StructConditionalComparable if all its fields are comparable.

Struct Comparability#

A struct can be compared with == or != if all of its fields are of comparable types.

eg.

type Point struct {
    X, Y int
}

p1 := Point{1, 2}
p2 := Point{1, 2}
fmt.Println(p1 == p2) // true
type Record struct {
    Data []int // Slice is not comparable
}

r1 := Record{Data: []int{1}}
r2 := Record{Data: []int{1}}
// fmt.Println(r1 == r2) // compile error: struct containing []int cannot be compared

new vs make#

Featurenew(T)make(T, ...)
Return TypePointer (*T)Value (T)
AllocationZeroes memoryInitializes internal data structure
Supported TypesAll typesSlice, Map, Channel only

eg.

p := new(int)        // *int, points to 0
s := make([]int, 10) // []int, initialized with len 10

new is rarely used in practice. For structs, the composite literal &T{} is preferred as it allows initializing fields.

Channel vs Mutex#

FeatureChannelMutex
Primary GoalCommunication / OrchestrationMemory Protection / Serialization
OwnershipTransfers data ownershipProtects shared ownership
ComplexitySuitable for complex coordinationSuitable for simple state protection
PerformanceSlower (scheduler overhead)Faster (low-level locking)

Guidelines#

Based on Concurrency in Go (Katherine Cox-Buday):

  • If you are coordinating goroutines or tracking a value as it is transformed by a series of goroutines, use channels.
  • If you are sharing access to a field in a struct, use mutexes.
  • If you discover a critical performance issue when using channels and cannot find any other way to fix the issue, modify your code to use a mutex.

# go