我有一个定义了函数的 Go 程序。我还有一张地图,每个功能都应该有一个键。我怎样才能做到这一点?
我已经尝试过了,但这不起作用。
func a(参数字符串){ } 米:=地图[字符串]函数{ 'a_func':一个, } 对于键,值:= 范围 m { 如果键 == 'a_func' { 值(参数) } }
你想做这样的事情吗?我已经修改了示例以使用不同类型和数量的函数参数。
package main
import "fmt"
func f(p string) {
fmt.Println("function f parameter:", p)
}
func g(p string, q int) {
fmt.Println("function g parameters:", p, q)
}
func main() {
m := map[string]interface{}{
"f": f,
"g": g,
}
for k, v := range m {
switch k {
case "f":
v.(func(string))("astring")
case "g":
v.(func(string, int))("astring", 42)
}
}
}
m := map[string]func(string, string)
如果您知道签名(并且所有功能都具有相同的签名)就可以工作我认为这比使用 interface{} 更干净/更安全
如果函数是相同的接口,您可以定义一个类型。
package main
import "log"
type fn func (string)
func foo(msg string) {
log.Printf("foo! Message is %s", msg)
}
func bar(msg string) {
log.Printf("bar! Message is %s", msg)
}
func main() {
m := map[string] fn {
"f": foo,
"b": bar,
}
log.Printf("map is %v", m)
m["f"]("Hello")
m["b"]("World")
}
@Seth Hoenig的回答对我帮助最大,但我只想补充一点,Go 也接受具有定义返回值的函数:
package main
func main() {
m := map[string]func(string) string{
"foo": func(s string) string { return s + "nurf" },
}
m["foo"]("baz") // "baznurf"
}
如果您认为它很难看,您可以随时使用类型(请参阅@smagch的回答)。
我使用了map[string]func (a type, b *type)我传递了一个字符串来搜索地图和一个指针来修改切片。
希望有帮助!
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"
}
这是我让它在我的情况下工作的方式:
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"
}