Middle+
How are arguments passed to a function — by value or by reference?
sobes.tech AI
Answer from AI
In Go, function arguments are passed by value. This means that when calling a function, a copy of the value is passed to the function's parameter.
However, if a pointer is passed, then the value of the pointer (which points to the original data) is copied. This allows indirect modification of the data the pointer points to.
Example:
func increment(val int) {
val++
}
func incrementPointer(val *int) {
(*val)++
}
func main() {
a := 5
increment(a) // a remains 5
incrementPointer(&a) // a becomes 6
}
In summary: basic types are passed by value, but pointers can be used to modify the original data.