ProgrammingBackend Developer

Explain how Go handles memory when passing maps and slices to functions, and what potential issues may arise?

Pass interviews with Hintsage AI assistant

Answer.

In Go, the map structure is always passed by value, but this value contains a pointer to the internal structures of the map itself (under the hood — a hash table). Therefore, if you pass a map to a function and modify its contents inside the function (add/remove elements), the changes will be visible outside. Slices behave similarly — the slice structure is copied, but not the actual data array: the slice contains a pointer to the array, its length, and capacity. If you modify values by index inside the function, the original array will also change. However, if you assign a new slice from within the function (for example, reslicing), the original variable will not change.

func updateMap(m map[string]int) { m["key"] = 42 // Changes are visible outside! } func updateSlice(s []int) { s[0] = 99 // The original array is modified }

Trick Question.

Why do changes to maps and slices inside a function affect the "original" when passed to the function?

Answer: Because only the pointer structure is copied, while the actual data remains shared — any changes affect the same memory block.

Examples of real errors due to misunderstanding of this topic.


Story

In a fintech project, a map with configuration settings was passed to different services, assuming that local changes would not impact the shared map. As a result, one service altered values, leading to bugs in other modules that received unexpectedly changed configurations.


Story

In an analytics microservice, a slice was passed, expecting to get independent copies. But the function inside changed values by index, leading to distorted data in the report, as the original array was unexpectedly modified.


Story

In game servers, a map was used to store user sessions and was concurrently passed to several goroutines. It was assumed that each goroutine was working with its copy, but in reality, a data race occurred and sessions were partially lost.