I'm still new to programming. Forgive my lack of computer science knowledge. Not sure if this question is specific to Golang or computer science in general...
I always thought that functions do not alter variables/data held outside their own scope unless you use a return statement back into the other scope, or unless they are higher in the hierarchy of scopes. One may argue that functions f1
and f2
in this example are called from a lower scope. However, this still doesn't explain why I'm getting different results for variable num
and nums
.
package main
import "fmt"
func f1(a int) {
a = 50 // this will not work, as it shouldn't
}
func f2(a ...int) {
a[0] = 50 // this will work without return statement
a[1] = 50 // this will work without return statement
}
func main() {
num := 2
nums := []int{2, 2}
f1(num)
f2(nums...)
fmt.Printf("function f1 doesn't affect the variable num and stays: %v\n", num)
fmt.Printf("function f2 affects the variable nums and results in: %v", nums)
Questions:
- Why doesn't
f2
require a return statement to modify nums like num would withinf1
? - Golang functions are said to pass values (rather than reference), shouldn't that force the function to return copies?
- Can this happen in other languages? (I think I may have seen this in other languages).