Sobes.tech
Junior — Middle

How are arguments passed to functions in Go?.

sobes.tech AI

Answer from AI

In the Go language, function arguments are passed by value, meaning they are copied upon call. This means that changes to parameters inside the function do not affect the variables passed to it, unless a pointer is passed.

Example of passing by value:

func increment(x int) {
    x = x + 1
}

func main() {
    a := 5
    increment(a)
    fmt.Println(a) // Will print 5, as a did not change
}

If you need to change the value of a variable from the calling code, pass a pointer:

func incrementPtr(x *int) {
    *x = *x + 1
}

func main() {
    a := 5
    incrementPtr(&a)
    fmt.Println(a) // Will print 6
}

Thus, Go uses pass-by-value, but with pointers, you can achieve pass-by-reference.

How are arguments passed to functions in Go?. — Golang - sobes.tech