gpt4 book ai didi

go - 存储通用函数

转载 作者:IT王子 更新时间:2023-10-29 02:16:06 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com