英文:
Can I create an associative array of different objects in Go?
问题
我想将某种类型的实例作为关联数组中的元素。我应该使用什么类型?
var objects // ???
// 构造函数将返回 IndexController 类型的实例
objects["IndexController"] = index.Constructor()
fmt.Println(objects)
谢谢!
英文:
I want to set an instance of a some type as an element in an associative array. What type should I use?
var objects //???
//The constructor will return instance of the IndexController type
objects["IndexController"] = index.Constructor()
fmt.Println(objects)
I will be thankful!
答案1
得分: 2
Go地图通常是同质的(每个值都是相同类型的)。如果你想要每个索引对应不同的类型,你可以创建一个包含所有对象支持的某个接口的数组。如果你不需要这些对象支持任何方法,你可以使用空接口interface{}
。
objects := make(map[string]interface{})
objects["IndexController"] = somethingThatReturnsAnIndexController()
英文:
Go maps are generally homogenous (each value is of the same type). If you want a different type per index, you can make an array of some interface that all of the objects in the array support. If you don't need the objects to support any methods at all, you can use the empty interface interface{}
.
objects := make(map[string]interface{})
objects["IndexController"] = somethingThatReturnsAnIndexController()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论