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

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

Types of specific positions in array of arrays?

问题

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

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

mapOfResults = ThingDoer([
  ["One",    int,    -1,    true],
  ["Flying", string, "",    true],
  ["Banana", bool,   false, true]
])

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

我指的是这个结构:

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

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

英文:

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

mapOfResults = ThingDoer([
  ["One",    int,    -1,    true],
  ["Flying", string, "",    true],
  ["Banana", bool,   false, true]
])

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:

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

How do I define the types for such a parameter?

答案1

得分: 3

请尝试这样做:

type ConfigItem struct {
    Name          string
    Value         interface{}
    SomethingElse bool
}

mapOfResults := ThingDoer([]ConfigItem{
    {"One", -1, true},
    {"Flying", "", true},
    {"Banana", false, true},
})

func ThingDoer(config []ConfigItem) map[foo]bar {
    for _, item := range config {
        switch v := item.Value.(type) {
        case int:
            // v 是 int 类型
        case bool:
            // v 是 bool 类型
        case string:
            // v 是 string 类型
        }
    }
}

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

playground 示例

英文:

Try this:

 type ConfigItem struct {
    Name string
    Value interface{}
    SomethingElse bool
 }

mapOfResults = ThingDoer([]ConfigItem{
  {"One",    -1,    true},
  {"Flying", "",    true},
  {"Banana", false, true},
})

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

func ThingDoer(config []ConfigItem) map[foo]bar {
    for _, item := range config {
      switch v := item.Value.(type) {
      case int:
        // v is int
      case bool:
        // v is bool
      case string:
        // v is string
      }
    }
 }

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:

确定