Why I cannot take the Address of & a function in golang but can for a function value

huangapple go评论82阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年3月15日 22:46:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/75746330.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定