Sobes.tech
Senior

What data types in Go are reference types?

sobes.tech AI

Answer from AI

In Go, reference types are those that store a pointer to a memory area rather than the data itself. They include:

  • Pointers (*Type) — store the address of a value.
  • Slices ([]Type) — a structure containing a pointer to an array, length, and capacity.
  • Maps — internally implemented via hash tables, passed by reference.
  • Channels (chan) — a reference type for communication between goroutines.
  • Functions — function variables are passed by reference.

For example, when passing a slice to a function, a structure with a pointer is copied, but the elements of the array it points to are not copied. This allows efficient handling of large data volumes without copying.

func modify(slice []int) {
    slice[0] = 100
}

func main() {
    s := []int{1, 2, 3}
    modify(s)
    fmt.Println(s) // [100 2 3]
}