【发布时间】:2020-06-29 19:06:10
【问题描述】:
我还是编程新手。原谅我缺乏计算机科学知识。不确定这个问题是否特定于 Golang 或一般的计算机科学......
我一直认为函数不会改变它们自己作用域之外的变量/数据,除非你使用 return 语句回到另一个作用域,或者除非它们在作用域的层次结构中更高。有人可能会争辩说,此示例中的函数 f1 和 f2 是从较低范围调用的。但是,这仍然不能解释为什么变量 num 和 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)
问题:
- 为什么
f2不需要return 语句来修改num 之类的num 会在f1内吗? - Golang 函数被称为传递值(而不是引用), 这不应该强制函数返回副本吗?
- 这可以在其他语言中发生吗? (我想我可能有 在其他语言中看到过)。
【问题讨论】:
标签: go computer-science