数组数组中特定位置的类型?

时间:2016-11-11 03:03:07

标签: arrays go types

我是Go的新手,我正在尝试用这个方面构建一个函数:

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

但我甚至无法想象它的签名(签名甚至是Go中适当的术语?它的所有参数的定义等)。

我在谈论这个结构:

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

如何定义此类参数的类型?

1 个答案:

答案 0 :(得分:2)

试试这个:

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

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

ThingDoer可以使用type switch来确定值类型:

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