go - 如何构建重复结构

标签 go struct

我有一个程序可以将 yamls 文件解析为对象(结构)。 我使用以下 repo 来做到这一点

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

例如在我的文件中:

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

我使用了下面的结构

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

type Install struct {
    Name       string
    Group      string
}

现在我有两个有点复杂的结构问题。

这是可能在 Dependency 结构中的条目,这是它在 yaml 文件中的样子

   requires:
       - name: db
       - type: mongo

也可以是

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

因为它有多个名称属性,我应该如何构建这个结构

此外,我在 yaml 中有字段

_type-version: "1.0.0"

当我像下面这样把它放在结构中时,我得到了错误,因为我使用了 -

type TypeVer struct{
    _Type-version string
}

如何克服这个问题?

最佳答案

yaml 包实际上允许您重新映射属性的名称,您可以使用它来处理您的 _type-version 属性。 以及您最初的问题:只需将 Requires 定义为与 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:\n%v\n\n", f)

    d, err := yaml.Marshal(&f)
    if err != nil {
        log.Fatalf("error: %v", err)
    }
    fmt.Printf("--- t dump:\n%s\n\n", string(d))
}

关于go - 如何构建重复结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47903113/

相关文章:

c - 如何从其成员地址获取结构的起始地址

ios - 在结构的运行时更改属性的名称

go - 删除 go-git 中的本地分支 : branch not found

mongodb - 按给定字段搜索嵌套对象数组

go - 如何使用AWS Lambda函数获取URL参数?

c - 结构内部结构

代码在 Windows 中有效,但在 Linux 中无效!为什么? 【简单的指针问题】

json - 我正在尝试打印 JSON

scala - 递归 GO 与 Scala

c - c 中的 ')' token 错误之前预期为 '*'