英文:
Why I cannot take the Address of & a function in golang but can for a function value
问题
在Go语言中声明一个函数如下:
func myFunc() {
}
如果声明一个函数指针并取函数的地址是错误的:
fp := &myFunc
会得到错误信息:"invalid operation: cannot take address of myFunc (value of type func())"。
然而,可以将函数赋值给一个函数值并取其地址:
functionValue := myFunc
fp := &functionValue
那么,"functionValue"和使用函数名"myFunc"有什么不同呢?它们不都是相同类型(func())吗?
英文:
Say I declare a func in golang:
func myFunc() {
}
It is an error to declare a function pointer taking the address of the function
fp := &myFunc
"invalid operation: cannot take address of myFunc (value of type func())"
However, I can assign it to a function value and take the address
functionValue := myFunc
fp := &function
Is "functionValue" any different from using the function name "myFunc"?
Aren't they both of the same type? (func())
答案1
得分: 3
myFunc
是一个函数。functionValue
是一个函数变量,它是指向函数的变量,并且是一个闭包。例如:
var x int
functionValue := func() int {return x}
在上面的例子中,functionValue
是一个带有闭包的函数变量,闭包中包含对x
的引用。
像myFunc
这样的命名函数没有与之关联的闭包。而像functionValue
这样的函数变量有一个闭包。当你将它赋值给myFunc
时,该闭包为空。当你像上面那样赋值时,它是非空的。因此,调用函数的机制与调用函数变量的机制不同。
函数变量的地址就是该变量的地址。
英文:
myFunc
is a function. functionValue
is a function variable, which is a variable pointing to a function, and a closure. For instance:
var x int
functionValue:=func() int {return x}
Above, functionValue
is a function variable with the closure containing a reference to x
.
A named function like myFunc
does not have a closure associated with it. A function variable like functionValue
has a closure. When you assign it to myFunc
that closure is empty. When you assign it like above, it is non-empty. Because of this, the mechanics of calling a function are different from calling a function variable.
The address of a function variable is just that, the address of that variable.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论