💻 Tech
In Go, there are reference and value types. Reference types like slices and maps allow you to share the references/pointers of the underlying data. That means when you copy a slice to another variable (or pass to a function), you’re copying the address, not the actual data. It can be utilized for performance reasons, but it’s not thread-safe.
In the example below, the function can mutate the slice. You don’t need to pass a pointer; slices are inherently operating under pointer semantics.
func main() {
letters := []string{"a", "b", "c"}
fmt.Println(letters)
mudar(letters)
fmt.Println(letters)
}
func mudar(letters []string) {
letters[0] = "x"
}
Output:
[a b c]
[x b c]
Same goes with maps.
func main() {
personneMap := map[int]string{
1: "francois",
2: "marie",
3: "michel",
}
fmt.Println(personneMap)
alterer(personneMap)
fmt.Println(personneMap)
}
func alterer(personneMap map[int]string) {
personneMap[1] = "x"
}
Output
map[1:francois 2:marie 3:michel]
map[1:x 2:marie 3:michel]