douba7784 2017-08-07 14:44
浏览 150
已采纳

具有动态模式的Golang和Yaml

I have a YAML structure with dynamic schema e.g. I can have the following yaml:

array:
  - name: myvar
    val: 1
  - name: mymap
    val: [ 1, 2]

Goyaml maps yaml to Go struct, which should declare definite type. Here, val is either a signle number, or an array or even a map.

Which is the best solution for this situation?

  • 写回答

1条回答 默认 最新

  • dongzhilian0188 2017-08-07 16:47
    关注

    I decided to add an answer showing a type assertion instead of the reflect package. You can decide which is best for your application. I personally prefer the builtin functions over the complexity of the reflect package.

    var data = `
    array:
      - name: myvar
        val: 1
      - name: mymap
        val: [1, 2]
    `
    
    type Data struct {
        Array []struct {
            Name string
            Val  interface{}
        }
    }
    
    func main() {
        d := Data{}
        err := yaml.Unmarshal([]byte(data), &d)
        if err != nil {
            log.Fatal(err)
        }
    
        for i := range d.Array {
            switch val := d.Array[i].(type) {
            case int:
                fmt.Println(val) // is integer
            case []int:
                fmt.Println(val) // is []int
            case []string:
                fmt.Println(val) // is []string
                //  .... you get the idea
            default:
                log.Fatalf("Type unaccounted for: %+v
    ", d.Array[i])
            }
        }
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行