Map of methods in Go

Yes. Currently:

actions := map[string]func(a string, b int){
        "add": func(a string, b int) { f.Add(a, b) },
}

Later: see the go11func document guelfi mentioned.


There is currently no way to store both receiver and method in a single value (unless you store it in a struct). This is currently worked on and it may change with Go 1.1 (see http://golang.org/s/go11func).

You may, however, assign a method to a function value (without a receiver) and pass the receiver to the value later:

package main

import "fmt"

type Foo struct {
    n int
}

func (f *Foo) Bar(m int) int {
    return f.n + m
}

func main() {
    foo := &Foo{2}
    f := (*Foo).Bar
    fmt.Printf("%T\n", f)
    fmt.Println(f(foo, 42))
}

This value can be stored in a map like anything else.

Tags:

Methods

Go