Go map of functions

Viewed 63259

I have Go program that has a function defined. I also have a map that should have a key for each function. How can I do that?

I have tried this, but this doesn't work.

func a(param string) {

}

m := map[string] func {
    'a_func': a,
}

for key, value := range m {
   if key == 'a_func' {
    value(param) 
   }
}
7 Answers

I used a map[string]func (a type, b *type) I passed a string to search the map and a pointer to modify the slice.

Hope that helps!

var Exceptions map[string]func(step string, item *structs.Item)

func SetExceptions() {
    Exceptions = map[string]func(a string, i *structs.Item){
        "step1": step1,
    }
}

func RunExceptions(state string, item *structs.Item) {
    method, methBool := Exceptions[state]
    if methBool {
        method(state, item)
    }
}

func step1(step string, item *structs.Item) {
    item.Title = "Modified"
}

Here is the way I made it work in my case:

package main

import (
    "fmt"
)

var routes map[string]func() string

func main() {
    routes = map[string]func() string{
        "GET /":      homePage,
        "GET /about": aboutPage,
    }

    fmt.Println("GET /", pageContent("GET /"))
    fmt.Println("GET /about", pageContent("GET /about"))
    fmt.Println("GET /unknown", pageContent("GET /unknown"))
    // Output:
    // GET / Home page
    // GET /about About page
    // GET /unknown 404: Page Not Found
}

func pageContent(route string) string {
    page, ok := routes[route]
    if ok {
        return page()
    } else {
        return notFoundPage()
    }
}

func homePage() string {
    return "Home page"
}

func aboutPage() string {
    return "About page"
}

func notFoundPage() string {
    return "404: Page Not Found"
}

https://play.golang.org/p/8_g6Di1OKZS

Hope this works for you(you can use interface{} instead any)

package main

import (

    "fmt"

)


func toon(v any) {

    fmt.Println(v)

}

func main() {

    names := map[string]any{

        "Function": toon,

    }

    names["Function"].(func(any))("a")

}
Related