'golang reflect get closure function pointer
please review code
package main
import (
"fmt"
"reflect"
)
func main() {
factory := func (name string) func(){
return func (){
fmt.Println(name)
}
}
f1 := factory("f1")
f2 := factory("f2")
pf1 := reflect.ValueOf(f1)
pf2 := reflect.ValueOf(f2)
fmt.Println(pf1.Pointer(), pf2.Pointer())
fmt.Println(pf1.Pointer() == pf2.Pointer())
f1()
f2()
}
the result:
4199328 4199328
true
f1
f2
Why get to the same address of the closure function! Or to how to get a unique address!
Solution 1:[1]
https://golang.org/pkg/reflect/#Value.Pointer
If v's Kind is Func, the returned pointer is an underlying code pointer, but not necessarily enough to identify a single function uniquely. The only guarantee is that the result is zero if and only if v is a nil func Value.
Solution 2:[2]
Actually, *func() type in Go is equivalent to void (*)(void) type in C. (I know this because I use cgo often.)
And a Go func() is defined as a literal, meaning that it's something like a blob of bytes that represent machine code, rather than a function pointer.
Note that everything is passed by value in Go, and even a function is not an exception.
var f1 func() = ...
reflect.ValueOf(f1)
When you do that, I think you're trying to get the first 8 bytes of a code block called f1, and that is not an address to that function.
In current version of Go you can't take an address of a func() because an anonymous func() is only a literal denoting a code block that's located nowhere in memory. So you can't get an address to that.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | user1431317 |
| Solution 2 |
