Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map of methods in Go

Tags:

methods

go

I have several methods that I'm calling for some cases (like Add, Delete, etc..). However over time the number of cases is increasing and my switch-case is getting longer. So I thought I'd create a map of methods, like Go map of functions; here the mapping of functions is trivial. However, is it possible to create a map of methods in Go?

When we have a method:

func (f *Foo) Add(a string, b int) { }

The syntax below create compile-time error:

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

Is it possible to create a map of methods in Go?

like image 363
Fatih Arslan Avatar asked Feb 26 '13 13:02

Fatih Arslan


People also ask

Does Go have a map function?

One of the most useful data structures in computer science is the hash table. Many hash table implementations exist with varying properties, but in general they offer fast lookups, adds, and deletes. Go provides a built-in map type that implements a hash table.

How do you create a map in Go?

Go by Example: Maps Maps are Go's built-in associative data type (sometimes called hashes or dicts in other languages). To create an empty map, use the builtin make : make(map[key-type]val-type) . Set key/value pairs using typical name[key] = val syntax. Printing a map with e.g. fmt.

What is a map in Go?

Maps are used to store data values in key:value pairs. Each element in a map is a key:value pair. A map is an unordered and changeable collection that does not allow duplicates. The length of a map is the number of its elements.

How do I add a map in Golang?

Create a map in Golang [string] - indicates that keys of the map are of string type. float32 - indicates that values of the map are of float type. {Golang", "Java", "Python"} - keys of the map. {85, 80, 81} - values of the map.


2 Answers

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.

like image 110
zzzz Avatar answered Oct 16 '22 15:10

zzzz


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.

like image 24
guelfey Avatar answered Oct 16 '22 16:10

guelfey