Go函数映射

huangapple go评论101阅读模式
英文:

Go map of functions

问题

我有一个Go程序,其中定义了一个函数。我还有一个应该为每个函数设置一个键的映射。我该如何做到这一点?

我尝试了以下方法,但它不起作用。

func a(param string) {

}

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

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

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.
<pre>
func a(param string) {

}

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

for key, value := range m {
if key == 'a_func' {
value(param)
}
}
</pre>

答案1

得分: 85

你是否想要做类似这样的事情?我已经修改了示例,使用了不同类型和数量的函数参数。

package main

import "fmt"

func f(p string) {
    fmt.Println("函数 f 的参数:", p)
}

func g(p string, q int) {
    fmt.Println("函数 g 的参数:", p, q)
}

func main() {
    m := map[string]interface{}{
        "f": f,
        "g": g,
    }
    for k, v := range m {
        switch k {
        case "f":
            v.(func(string))("一个字符串")
        case "g":
            v.(func(string, int))("一个字符串", 42)
        }
    }
}
英文:

Are you trying to do something like this? I've revised the example to use varying types and numbers of function parameters.

package main

import &quot;fmt&quot;

func f(p string) {
	fmt.Println(&quot;function f parameter:&quot;, p)
}

func g(p string, q int) {
	fmt.Println(&quot;function g parameters:&quot;, p, q)
}

func main() {
	m := map[string]interface{}{
		&quot;f&quot;: f,
		&quot;g&quot;: g,
	}
	for k, v := range m {
		switch k {
		case &quot;f&quot;:
			v.(func(string))(&quot;astring&quot;)
		case &quot;g&quot;:
			v.(func(string, int))(&quot;astring&quot;, 42)
		}
	}
}

答案2

得分: 80

m := map[string]func(string, string)

如果你知道签名(并且所有的函数都有相同的签名),这个方法是可行的。
我认为这比使用接口更清晰/更安全。

英文:
m := map[string]func(string, string)

Works if you know the signature (and all the funcs have the same signature)
I think this is cleaner/safer than using interface{}

答案3

得分: 24

你可以定义一个类型,如果函数具有相同的接口。

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")
}
英文:

You can define a type if functions are same interface.

package main

import &quot;log&quot;

type fn func (string)

func foo(msg string) {
  log.Printf(&quot;foo! Message is %s&quot;, msg)
}

func bar(msg string) {
  log.Printf(&quot;bar! Message is %s&quot;, msg)
}

func main() {
  m := map[string] fn {
    &quot;f&quot;: foo,
    &quot;b&quot;: bar,
  }
  log.Printf(&quot;map is %v&quot;, m)
  m[&quot;f&quot;](&quot;Hello&quot;)
  m[&quot;b&quot;](&quot;World&quot;)
}

答案4

得分: 16

@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**的答案)。

英文:

@Seth Hoenig's answer helped me best, but I just wanted to add that Go accepts functions with defined return value as well:

package main

func main() {
    m := map[string]func(string) string{
        &quot;foo&quot;: func(s string) string { return s + &quot;nurf&quot; },
    }

    m[&quot;foo&quot;](&quot;baz&quot;) // &quot;baznurf&quot;
}

If you think it's ugly, you could always use a type (see @smagch's answer).

答案5

得分: 2

我使用了一个map[string]func (a type, b *type),我传递了一个字符串来搜索map,并传递一个指针来修改切片。

希望对你有所帮助!

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";
}
英文:

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){
		&quot;step1&quot;: 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 = &quot;Modified&quot;
}

答案6

得分: 2

希望这对你有用(你可以使用interface{}代替any)

package main

import (

	"fmt"

)


func toon(v interface{}) {

	fmt.Println(v)

}

func main() {

	names := map[string]interface{}{

		"Function": toon,

	}

	names["Function"].(func(interface{}))("a")

}
英文:

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

package main

import (

	&quot;fmt&quot;

)


func toon(v any) {

	fmt.Println(v)

}

func main() {

	names := map[string]any{

		&quot;Function&quot;: toon,

	}

	names[&quot;Function&quot;].(func(any))(&quot;a&quot;)

}

答案7

得分: 1

这是我在我的情况下使其工作的方法:

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"))
    // 输出:
    // GET / 主页
    // GET /about 关于页面
    // GET /unknown 404:页面未找到
}

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

func homePage() string {
	return "主页"
}

func aboutPage() string {
	return "关于页面"
}

func notFoundPage() string {
	return "404:页面未找到"
}

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

英文:

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

package main

import (
	&quot;fmt&quot;
)

var routes map[string]func() string

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

	fmt.Println(&quot;GET /&quot;, pageContent(&quot;GET /&quot;))
	fmt.Println(&quot;GET /about&quot;, pageContent(&quot;GET /about&quot;))
	fmt.Println(&quot;GET /unknown&quot;, pageContent(&quot;GET /unknown&quot;))
    // 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 &quot;Home page&quot;
}

func aboutPage() string {
	return &quot;About page&quot;
}

func notFoundPage() string {
	return &quot;404: Page Not Found&quot;
}

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

huangapple
  • 本文由 发表于 2011年7月21日 05:54:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/6769020.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定