在golang中填充struct数组

时间:2015-01-17 15:33:04

标签: go

我有像

这样的结构
type Coverage struct {
  neoCoverage        []NeoCoverage
  ApocCoverage       []ApocCoverage
  ApocConfigCoverage []ApocConfigCoverage
}

type NeoCoverage struct {
  Name   string
  Number string
}

那么我应该如何填写coverage结构?

这是我的尝试方式。

coverage = Coverage{
 []neoCoverage: NeoCoverage{
     Name:   "xyz",
     Number: "xyz123",
   },
 }

1 个答案:

答案 0 :(得分:3)

您还可以省略数组中的冗余Type声明。以Alper的代码库为例。

package main

import "fmt"

func main() {
    type NeoCoverage struct {
         Name   string
         Number string
    }

    type Coverage struct {
        neoCoverage []NeoCoverage
    }

    coverage := Coverage {
        neoCoverage: []NeoCoverage {
            { Name: "xyz", Number: "xyz123" },
            { Name: "abc", Number: "abc123" },
        },
    }

    fmt.Println(coverage)
}

输出:

{[{xyz xyz123} {abc abc123}]}