Home > Backend Development > Golang > Go's Value vs. Pointer Semantics: When Do Functions Modify Original Variables?

Go's Value vs. Pointer Semantics: When Do Functions Modify Original Variables?

Patricia Arquette
Release: 2024-12-22 17:04:16
Original
279 people have browsed it

Go's Value vs. Pointer Semantics: When Do Functions Modify Original Variables?

Value and Pointer Semantics in Go

Value semantics refers to the passing of a copy of a variable's value to a function or method, allowing the function to only modify this copy without affecting the original value.

Pointer semantics, on the other hand, allows a function to modify the original value by passing a pointer to it. Although Go passes everything by value, some types exhibit pointer semantics.

Example: Value Semantics

Consider the following example:

func main() {
    i := 1
    fmt.Println("double:", double(i))
    fmt.Println("original i:", i)
}

func double(i int) int {
    i *= 2
    return i
}
Copy after login

Here, passing i to double creates a copy, and any modification in double doesn't affect the original i variable.

Example: Pointer Semantics

To demonstrate pointer semantics, let's use a slice:

func main() {
    is := []int{1, 2}
    fmt.Println("double:", doubles(is))
    fmt.Println("original is:", is)
}

func doubles(is []int) []int {
    for i := range is {
        is[i] *= 2
    }
    return is
}
Copy after login

In this case, passing is to doubles creates a copy of the slice header, but the pointer to the underlying array remains the same. Any modification to the elements in doubles is therefore reflected in the original is slice.

Reasoning

In Go, everything is passed by value, but slices are composed of a structure containing a pointer to an array. When a slice is passed, the slice header copy includes the same pointer, allowing functions to modify the original array elements. This behavior is known as pointer semantics.

Conclusion

Understanding value and pointer semantics is crucial in Go. It determines whether functions can modify original values or only copies.

The above is the detailed content of Go's Value vs. Pointer Semantics: When Do Functions Modify Original Variables?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template