go - 我可以在 Go 中创建不同对象的关联数组吗?

标签 go

我想将某种类型的实例设置为关联数组中的元素。我应该使用什么类型?

var objects //???

//The constructor will return instance of the IndexController type
objects["IndexController"] = index.Constructor()

fmt.Println(objects)

我将不胜感激!

最佳答案

Go map 通常是同质的(每个值都是同一类型)。如果你想要每个索引不同的类型,你可以创建一个数组中的所有对象都支持的一些接口(interface)。如果您根本不需要对象支持任何方法,则可以使用空接口(interface) interface{}

objects := make(map[string]interface{})
objects["IndexController"] = somethingThatReturnsAnIndexController()

关于go - 我可以在 Go 中创建不同对象的关联数组吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23173545/

相关文章:

regex - 如何仅匹配一个字母词

go - 将带参数的函数传递给 time.AfterFunc

amazon-web-services - lambda 层与 Go 兼容吗?

api - Go 语言 HTTPS API

json - 如何在输入时跳过 Struct 中的 JSON 字段并在输出中显示它们,以及在输入中接受某些字段并在 Golang 中在输出中跳过它们?

google-app-engine - 您的应用程序不在 GOPATH 上 - 部署到 app Engine go1.12

pointers - 从 (type *int) 到 int 类型的类型转换

git - 如何使用语义版本构建 Go Module?

go - 如何在Golang中将变量参数传递给Sprintf

go - 为什么这个 goroutine 会泄漏?