ProgrammingBackend Developer

How is work with immutable and mutable data structures implemented in Go? Provide examples where this is important to consider when programming.

Pass interviews with Hintsage AI assistant

Answer

In Go, most built-in data types (e.g., int, float, struct) are mutable when declared as variables because when passed by value, the entire structure or value is copied. However, there is a nuance: slices (slice), maps (map), and channels (channel) are reference types with their own internal logic for data storage.

Basic types:

x := 10 y := x // Here, a copy of the value is created, x and y are not linked y = 20 // x will remain 10

Slices:

a := []int{1,2,3} b := a // reference to the same underlying array b[0] = 100 // now a[0] == 100

This is important when a function or method takes a struct or slice because changes may or may not affect the original data, depending on the data type and the way it is passed (by value or by reference).

Trick Question

Question: "If you assign one slice to another, do you get a deep copy or do both point to the same data?"

Answer: With simple assignment of slices (b := a) — both point to the same underlying array, but have independent length and capacity. Changes made through one of the slices to the underlying array data are visible in the other.

Example:

a := []int{1,2,3} b := a b[0] = 42 fmt.Println(a) // [42 2 3]

To make a deep copy, use copy:

c := make([]int, len(a)) copy(c, a) c[0] = 99 fmt.Println(a) // [42 2 3], c is an independent copy

Story

Data filtration service started returning unexpected results: One developer was passing slices between multiple functions without copying, changing their state. Due to modifications of slices in different places, the application logic was broken, and strange bugs in the data could not be caught for a long time.


Story

Data loss after passing a struct: In one project, an obligatory field was mistakenly removed from the struct during data serialization because the object was passed by reference, not creating a copy. As a result, critical information was lost in production.


Story

Error with concurrent access to map: A developer copied a reference to a map, thinking that changes would not affect the original, as is common in other languages. This caused a data race when working in different goroutines, leading to application crashes.