golang reflect get closure function pointer

Viewed 2410

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!

3 Answers

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.

Related