数组中特定位置的类型有哪些?

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

Types of specific positions in array of arrays?

问题

我是你的中文翻译助手,以下是翻译好的内容:

我在Go语言方面还是个新手,我正在尝试构建一个具有以下一般性质的函数:

  1. mapOfResults = ThingDoer([
  2. ["One", int, -1, true],
  3. ["Flying", string, "", true],
  4. ["Banana", bool, false, true]
  5. ])

但是我甚至无法确定它的签名(在Go语言中,签名是否是正确的术语?以及所有参数的定义等)。

我指的是这个结构:

  1. func ThingDoer(config ThisIsWhatICannotFigure) map[string]Results {
  2. // 函数体
  3. }

如何为这样的参数定义类型?

英文:

I'm very much a newb in Go and I'm trying to build a function with this general aspect:

  1. mapOfResults = ThingDoer([
  2. ["One", int, -1, true],
  3. ["Flying", string, "", true],
  4. ["Banana", bool, false, true]
  5. ])

But I cannot even figure its signature (is signature even the proper term for it in Go? the definition of all its params etc).

I'm talking about this construct:

  1. func ThingDoer(config ThisIsWhatICannotFigure) map[string]Results {
  2. // the body of my function
  3. }

How do I define the types for such a parameter?

答案1

得分: 3

请尝试这样做:

  1. type ConfigItem struct {
  2. Name string
  3. Value interface{}
  4. SomethingElse bool
  5. }
  6. mapOfResults := ThingDoer([]ConfigItem{
  7. {"One", -1, true},
  8. {"Flying", "", true},
  9. {"Banana", false, true},
  10. })
  11. func ThingDoer(config []ConfigItem) map[foo]bar {
  12. for _, item := range config {
  13. switch v := item.Value.(type) {
  14. case int:
  15. // v 是 int 类型
  16. case bool:
  17. // v 是 bool 类型
  18. case string:
  19. // v 是 string 类型
  20. }
  21. }
  22. }

ThingDoer 函数可以使用 类型开关 来确定值的类型。

playground 示例

英文:

Try this:

  1. type ConfigItem struct {
  2. Name string
  3. Value interface{}
  4. SomethingElse bool
  5. }
  6. mapOfResults = ThingDoer([]ConfigItem{
  7. {"One", -1, true},
  8. {"Flying", "", true},
  9. {"Banana", false, true},
  10. })

The ThingDoer can use a type switch to determine the value types:

  1. func ThingDoer(config []ConfigItem) map[foo]bar {
  2. for _, item := range config {
  3. switch v := item.Value.(type) {
  4. case int:
  5. // v is int
  6. case bool:
  7. // v is bool
  8. case string:
  9. // v is string
  10. }
  11. }
  12. }

playground example

huangapple
  • 本文由 发表于 2016年11月11日 11:03:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/40540490.html
匿名

发表评论

匿名网友

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

确定