Non puoi farlo direttamente, come già detto, ma è possibile sorta di è falso fare qualcosa di simile:
package main
import "fmt"
func a(i int) int {
return i + 1
}
func b(i int) int {
return i + 2
}
type Function func(int)int
type FunctionWrapper struct {
f *Function
}
var fnMap = make(map[string]FunctionWrapper)
// MakeFunctionWrapper returns a unique FunctionWrapper per Function pointer, using fnMap to avoid having multiple values for the same function
func MakeFunctionWrapper(f Function) FunctionWrapper {
key := fmt.Sprintf("%#v", f)
data, ok := fnMap[key]
if !ok {
data = FunctionWrapper{&f}
fnMap[key] = data
}
return data
}
func main() {
functions := make(map[FunctionWrapper]bool)
fa := MakeFunctionWrapper(a)
fb := MakeFunctionWrapper(b)
fb2 := MakeFunctionWrapper(b)
functions[fa] = true
functions[fb] = true
functions[fb2] = false // This overwrites the previous value since fb is essentially the same as fb2
fmt.Println(functions[fa]) // "true"
fmt.Println(functions[fb]) // "false"
fmt.Println(functions[fb2]) // "false"
}
Check it out on the Go playground
Questo è un po 'macchinoso, e onestamente penso che sia una pessima idea usare essenzialmente la versione stringa di un puntatore come chiave della mappa. Ma ... è almeno un'opzione se ne hai davvero bisogno.
Qual è il caso esatto uso? Un'interfaccia non sarebbe più semantica e più estensibile qui? –
Ho bisogno di sapere se una funzione che ho ottenuto da un 'trie' è una funzione creata dalla funzione' X' o no .. – Kokizzu