Sobes.tech
Junior — Middle

How are parameters passed in functions in Go?

sobes.tech AI

Answer from AI

In the Go language, function parameters are passed by value, meaning they are copied when the function is called. This means that inside the function, you work with a copy of the passed value, and changes to the parameter do not affect the original.

However, if the parameter is a pointer, slice, map, channel, or interface, then the structure itself that contains a reference to the data is copied, and changes through this reference can affect the original data.

Example of parameter passing:

func increment(x int) {
    x = x + 1 // only the copy is changed, the original remains unchanged
}

func incrementPointer(x *int) {
    *x = *x + 1 // the value at the address is changed, the original is modified
}

func main() {
    a := 5
    increment(a)
    fmt.Println(a) // will print 5

    incrementPointer(&a)
    fmt.Println(a) // will print 6
}