【问题标题】:Types of specific positions in array of arrays?数组数组中特定位置的类型?
【发布时间】:2017-03-25 05:48:27
【问题描述】:

我是 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
}

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

【问题讨论】:

    标签: arrays go types


    【解决方案1】:

    试试这个:

     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

    【讨论】:

    • 为我工作!显然,我必须稍等片刻才能接受您的回答。谢谢!
    猜你喜欢
    • 2017-07-10
    • 2020-09-05
    • 1970-01-01
    • 1970-01-01
    • 2014-08-11
    • 1970-01-01
    • 2021-03-01
    • 2016-02-03
    • 1970-01-01
    相关资源
    最近更新 更多