转到功能图

发布于 2024-11-25 11:17:09 字数 241 浏览 2 评论 0原文

我有一个定义了函数的 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.

func a(param string) {

}

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

短叹 2024-12-02 11:17:09

你想做这样的事情吗?我修改了示例以使用不同类型和数量的函数参数。

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)
        }
    }
}

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 "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)
        }
    }
}
謌踐踏愛綪 2024-12-02 11:17:09
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{}

╰ゝ天使的微笑 2024-12-02 11:17:09

如果函数是相同的接口,则可以定义类型。

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 "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")
}
农村范ル 2024-12-02 11:17:09

@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{
        "foo": func(s string) string { return s + "nurf" },
    }

    m["foo"]("baz") // "baznurf"
}

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

放赐 2024-12-02 11:17:09

希望这对您有用(您可以使用interface{}代替任何)

package main

import (

    "fmt"

)


func toon(v any) {

    fmt.Println(v)

}

func main() {

    names := map[string]any{

        "Function": toon,

    }

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

}

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")

}
大海や 2024-12-02 11:17:09

以下是我在我的案例中的工作方式:

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

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

早乙女 2024-12-02 11:17:09

我使用了 ma​​p[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"
}

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"
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文