go - 存储通用函数

标签 go

我想做这样的事情,但显然不可能以这种方式进行,我认为我想念一些东西。

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

最佳答案

你有一个类型不匹配,因为你的结构成员需要一个 func(param ...interface) 而你正试图传递一个 func(map[string]command)

参见 here有关接口(interface)类型如何工作的解释。

如果您如下更改代码并为结构成员提供简单的类型接口(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() {
    // Map to store commands
    commands := make(map[string]command)

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

试穿 Go Playground

关于go - 存储通用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29655299/

相关文章:

amazon-web-services - 将从 SNS 收到的 JSON 转发到 Lambda - GoLang

go - 是 slice2 := slice1 equal to slice2 := slice1[:] in GoLang?

GoLang 中的 HTML 部分

go - 创建处理程序如何工作?

go - 对于大内容,go io.copy 函数中的错误一致

go - 在一个事务中在 golang 中执行多个查询的惯用方式

go - 在用 GO 编写的 Hyperledger 链码中使用泛型类型的实例作为返回值类型

go - 为什么很多golang项目直接从GitHub导入?

javascript - 为具有需要编译的静态 Assets 的项目推荐的 Go 项目结构和构建系统?

HTTP 响应始终为空