Go map of functions

前端 未结 6 1494
春和景丽
春和景丽 2020-12-23 09:21

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 wo

6条回答
  •  囚心锁ツ
    2020-12-23 09:47

    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

提交回复
热议问题