存储一个通用函数

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

Store a generic function

问题

我想做类似这样的事情,但显然用这种方式是不可能的,我认为我漏掉了什么。

type command struct {
    help    string
    handler func(params ...interface{})
}

func showHelp(commands map[string]command) {
    fmt.Println("帮助:")
    for c, h := range commands {
        fmt.Println(c, "->", h.help)
    }
}

func main() {
    // 用于存储命令的映射
    commands := make(map[string]command)

    // 添加帮助命令
    commands["help"] = command{"显示此信息", showHelp}
}

以上是你提供的代码的翻译。

英文:

I would like to do something like this, but apparently it is not possible in this way, I think that there is something I miss.

type command struct {                                                            
    help string                                                                  
    handler func (params ...interface{})                                         
}                                                                                
                                                                             
func showHelp( commands map[string]command ) {                                   
    fmt.Println( "Help:" )                                                       
    for c, h := range commands {                                                 
        fmt.Println( c,"->" ,h.help )                                            
    }                                                                            
}                                                                                
                                                                             
func main() {                                                                
    // Map to store commands                                                     
    commands := make( map[string]command )                                       
                                                                             
    // Adding help command                                                       
    commands["help"] = command{ "show this information", showHelp }
}

答案1

得分: 1

你的代码中存在类型不匹配的问题,你的结构体成员期望一个 func(param ...interface{}) 类型,而你试图传递一个 func(map[string]command) 类型的函数给它。

关于接口类型的工作原理,请参考这里的解释。

如果你将代码修改如下,并且将结构体成员的类型简单地设置为 interface{},它就可以接受任何类型,包括函数类型,我认为这是你想要的。

package main

import "fmt"

type command struct {
	help    string
	handler interface{}
}

func showHelp(commands map[string]command) {
	fmt.Println("Help:")
	for c, h := range commands {
		fmt.Println(c, "->", h.help)
	}
}

func main() {
	// 用于存储命令的映射
	commands := make(map[string]command)

	// 添加帮助命令
	commands["help"] = command{"显示此信息", showHelp}
	showHelp(commands)
}

Go Playground上尝试一下吧。

英文:

You have a type mismatch in that your struct member expects an func(param ...interface) and you are trying to pass it a func(map[string]command)

See here for the explanation on how interface types work.

If you change your code as below and give the struct member simply type interface{} it can take any type including a function which I think is what you want.

package main

import "fmt"

type command struct {
	help    string
	handler interface{}
}

func showHelp(commands map[string]command) {
	fmt.Println("Help:")
	for c, h := range commands {
		fmt.Println(c, "->", h.help)
	}
}

func main() {
	// Map to store commands
	commands := make(map[string]command)

	// Adding help command
	commands["help"] = command{"show this information", showHelp}
	showHelp(commands)
}

Try in on the Go Playground

答案2

得分: 0

我认为你正在寻找这样的代码:

package main

import "fmt"

type command struct {
	help    string
	handler func()
}

func main() {
	c := command{}
	c.handler = func() {
		fmt.Println("Hello, playground")
	}
	c.handler()
}

至少这是我会这样做。在你的结构体上放一个类型为func的字段,然后在方便的地方使用闭包将一个方法分配给它。

英文:

I think you're looking for something like this;

package main

import "fmt"


type command struct {                                                            
    help string                                                                  
    handler func()                                        
}   


func main() {
	c := command{}
	c.handler = func () { 
	fmt.Println("Hello, playground")
	}
	c.handler()
}

At least this is how I would do it. Put a field of type func on your struct then in whatever place is convenient use a closure to assign a method to it.

答案3

得分: 0

你的处理程序中需要使用类型断言 - 这是泛型的代价。你的设计虽然不符合惯用方式,但可以作为概念验证而工作。

package main

import "fmt"

type command struct {
	help    string
	handler func(params ...interface{})
}

func showHelp(commands ...interface{}) {
	fmt.Println("Help:")
	for c, h := range commands[0].(map[string]command) { // 在这里进行类型断言
		fmt.Println(c, "->", h.help)
	}
}

func main() {
	// 用于存储命令的映射
	commands := make(map[string]command)

	// 添加帮助命令
	commands["help"] = command{"显示此信息", showHelp}
	commands["help"].handler(commands)
}

可以在这里查看代码:https://play.golang.org/p/c67TVcorL1

英文:

You will need type assertion in your handlers - cost of generics. Your design as is, non-idiomatic but can work just as proof_of_concept.

package main

import "fmt"

type command struct {
	help    string
	handler func(params ...interface{})
}

func showHelp(commands ...interface{}) {
	fmt.Println("Help:")
	for c, h := range commands[0].(map[string]command) { //type assertion here
		fmt.Println(c, "->", h.help)
	}
}

func main() {
	// Map to store commands
	commands := make(map[string]command)

	// Adding help command
	commands["help"] = command{"show this information", showHelp}
	commands["help"].handler(commands)
}

Works https://play.golang.org/p/c67TVcorL1

huangapple
  • 本文由 发表于 2015年4月16日 00:06:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/29655299.html
匿名

发表评论

匿名网友

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

确定