Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

map with function pointer as key in go

Tags:

People also ask

Can map keys be functions?

A Map 's keys can be any value (including functions, objects, or any primitive). The keys of an Object must be either a String or a Symbol . The keys in Map are ordered in a simple, straightforward way: A Map object iterates entries, keys, and values in the order of entry insertion.

Is map a pointer in Go?

Maps, like channels, but unlike slices, are just pointers to runtime types. As you saw above, a map is just a pointer to a runtime. hmap structure. Maps have the same pointer semantics as any other pointer value in a Go program.

Does Go have function pointers?

Go has pointers. A pointer holds the memory address of a value. The type *T is a pointer to a T value.

Are maps passed by value or reference in Golang?

They are not reference types (though they are indirect types). If you assign to a map value, you will break its relationship with other variables. Go has no reference types, everything is a value.


I recently used a map in one of my golang projects, that had function pointers as keys like this:

map[*functiontype] somestructtype

One of my colleagues said this was a bad idea, so now I am unsure of this being feasible. I initially deemed it ok, because method pointers can be checked for equality and are immutable. Can someone provide some reasoning on that matter?

Complete example:

package main

import "fmt"

type s struct {
    string
}

type f func() string
func func1() string { return "func 1" }
func func2() string { return "func 2" }

func main() {
    // make two functions and two pointers to them
    f1, f2 := func1, func2
    p1, p2 := (*f)(&f1), (*f)(&f2)

    // make a map of their function pointers
    m := make(map[*f]s)
    m[p1] = s{"struct 1"}
    m[p2] = s{"struct 2"}

    // print out the mapping
    printmapping(m, p1, p2)

    // reverse the pointers and have that printed
    p1, p2 = (*f)(&f2), (*f)(&f1)
    printmapping(m, p1, p2)
}

func printmapping(m map[*f]s, p1, p2 *f) {
    fmt.Println("pointer 1:", m[(*f)(p1)])
    fmt.Println("pointer 2:", m[(*f)(p2)])
}