search

What is the difference between Go's value types and reference types?

In Go, variables can hold values of either value types or reference types. The main difference between the two is in how they are stored and passed around in memory.

Value types are types whose values are stored directly in memory. When a value type is assigned to a new variable, a copy of the value is made and stored in the new variable. This means that changes made to one variable do not affect the other. Examples of value types in Go include basic types like **int**, **float**, and **bool**, as well as user-defined types like **struct** and **array**.

Reference types, on the other hand, are types whose values are stored in memory and accessed through a reference or pointer. When a reference type is assigned to a new variable, only the memory address where the value is stored is copied, not the actual value. This means that changes made to one variable will affect all variables that reference the same value. Examples of reference types in Go include slices, maps, and channels.

Here's an example to illustrate the difference between value types and reference types in Go:

func main() {
    // value types
    a := 10
    b := a
    b = 20
    fmt.Println(a, b) // prints "10 20"

    // reference types
    nums := []int{1, 2, 3}
    nums2 := nums
    nums2[0] = 10
    fmt.Println(nums, nums2) // prints "[10 2 3] [10 2 3]"
}

In this example, we have two variables **a** and **b** that hold values of type **int**. Since **int** is a value type, the value of **a** is copied into **b**. When we change the value of **b**, it does not affect the value of a.

We also have two variables **nums** and **nums2** that hold slices of **int**. Since slices are reference types, the memory address of the underlying array is copied into **nums2** when it is assigned to **nums2**. When we change the value of **nums2[0]**, it also changes the value of **nums[0]** since they both reference the same underlying array.

In summary, value types in Go store their values directly in memory, while reference types store their values in memory and are accessed through a reference or pointer. Understanding the difference between the two is important for managing memory and avoiding unexpected behavior in your code.

Related Questions You Might Be Interested