Junior — Middle
How is argument passing in functions implemented in Go?
sobes.tech AI
Answer from AI
In the Go language, function arguments are passed by value. This means that when a function is called, copies of the argument values are passed inside the function, and changes within the function do not affect the original variables.
If you need to modify the value of a variable from the calling code, you pass a pointer to that variable. Then the function receives the address and can change the value at that address.
Example of passing by value and by pointer:
package main
import "fmt"
func incrementByValue(x int) {
x = x + 1
}
func incrementByPointer(x *int) {
*x = *x + 1
}
func main() {
a := 5
incrementByValue(a)
fmt.Println(a) // Will print 5, as it was passed by value
incrementByPointer(&a)
fmt.Println(a) // Will print 6, as a pointer was passed
}