Home  >  Article  >  Backend Development  >  Why can't I get the address of the function in golang, but I can get the function value

Why can't I get the address of the function in golang, but I can get the function value

WBOY
WBOYforward
2024-02-10 19:30:20749browse

为什么我不能获取 golang 中函数的地址,但可以获取函数值

php editor Zimo will answer for you: Why can’t I get the address of the function in golang, but can I get the function value? In Golang, function values ​​can be obtained because function values ​​are a type that can be called. The address of the function is not obtainable, which is determined by Golang's design decision. Functions in Golang are first-class citizens and can be assigned, passed and called like other types. Therefore, function values ​​can be obtained and passed to other functions. However, Golang's function implementation is implemented through closures. Every time a function is created, a new closure instance is generated, so the address of the function is not fixed and cannot be obtained. Such a design can ensure the independence and safety of functions, while simplifying the process of memory management and garbage collection. So, although you can't get the address of the function, you can get the function value and call it.

Question content

Suppose I declare a function in golang:

func myfunc() {     
    }

It is an error to declare a function pointer using a function address

fp := &myfunc

"Invalid operation: Unable to get the address of myfunc (a value of type func())"

However, I can assign it to a function value and get the address

functionValue := myFunc
fp := &function

Is "functionvalue" any different than using the function name "myfunc"? Aren't they both of the same type? (Function ())

Solution

myfunc is a function. functionvalue is a function variable, which is a variable pointing to a function and a closure. For example:

var x int
functionValue:=func() int {return x}

Above, functionvalue is a function variable whose closure contains a reference to x.

Named functions like myfunc do not have closures associated with them. Function variables like functionvalue have a closure. The closure is empty when you assign it to myfunc. When you allocate it like above, it is non-null. Therefore, the mechanism of calling a function is different from calling a function variable.

The address of a function variable is the address of the variable.

The above is the detailed content of Why can't I get the address of the function in golang, but I can get the function value. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete