Can I create an associative array of different objects in Go?

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

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()

huangapple
  • 本文由 发表于 2014年4月20日 01:59:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/23173545.html
匿名

发表评论

匿名网友

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

确定