drtoaamk20278 2017-12-20 09:50
浏览 13
已采纳

如何建立重复结构

I have a program which parses yamls file to an objects (structs). I use the following repo to do it

https://github.com/go-yaml/yaml

for example in the file I have:

dependency :
  - name: ui
    type: runner
    cwd: /ui
    install:
       - name: api
         group: test

And I use the following struct for it

type Dependency struct {
    Name     string
    Type     string
    CWD      string
    Install  []Install
    //here I have the issue
    Requires   ? 
}

type Install struct {
    Name       string
    Group      string
}

Now I have two few issue with a bit complex struct.

This is the entry which could be inside the Dependency struct and this is how it look in the yaml file

   requires:
       - name: db
       - type: mongo

but it also can be

requires:
       - name: db
       - name: rst
       - name: test
       - name: test2

Since it have multiple name properties how should I got build this struct

In addition I've field in the yaml

_type-version: "1.0.0"

when I put it inside struct like following I got error since I use -

type TypeVer struct{
    _Type-version string
}

How to overcome this?

  • 写回答

1条回答 默认 最新

  • dsc56927 2017-12-20 10:27
    关注

    The yaml package actually allows you to remap the the name for the properties, you can use this to handle your _type-version Property. And your initial question: Just define Requires the same as Install:

    package main
    
    import (
        "fmt"
        "log"
    
        "github.com/go-yaml/yaml"
    )
    
    type File struct {
        TypeVersion string `yaml:"_type-version"`
        Dependency []Dependency
    }
    
    type Dependency struct {
        Name     string
        Type     string
        CWD      string
        Install  []Install
        Requires []Requires
    }
    
    type Install struct {
        Name  string
        Group string
    }
    
    type Requires struct {
        Name string
        Type string
    }
    
    var data = `
    _type-version: "1.0.0"
    dependency:
      - name: ui
        type: runner
        cwd: /ui
        install:
           - name: api
             group: test
        requires:
          - name: db
          - type: mongo
          - name: rst
          - name: test
          - name: test2
    `
    
    func main() {
        f := File{}
    
        err := yaml.Unmarshal([]byte(data), &f)
        if err != nil {
            log.Fatalf("error: %v", err)
        }
        fmt.Printf("--- t:
    %v
    
    ", f)
    
        d, err := yaml.Marshal(&f)
        if err != nil {
            log.Fatalf("error: %v", err)
        }
        fmt.Printf("--- t dump:
    %s
    
    ", string(d))
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?