猿问

在golang中填充结构数组

我有结构像


type Coverage struct {

  neoCoverage        []NeoCoverage

  ApocCoverage       []ApocCoverage

  ApocConfigCoverage []ApocConfigCoverage

}


type NeoCoverage struct {

  Name   string

  Number string

}

那么我应该如何填充覆盖结构?


在这里,我是如何尝试的。


coverage = Coverage{

 []neoCoverage: NeoCoverage{

     Name:   "xyz",

     Number: "xyz123",

   },

 }


DIEA
浏览 408回答 2
2回答

偶然的你

像下面这样package mainimport "fmt"func main() {    type NeoCoverage struct {        Name   string        Number string    }    type Coverage struct {        neoCoverage []NeoCoverage    }    coverage := Coverage {        neoCoverage: []NeoCoverage {            NeoCoverage{ Name: "xyz", Number: "xyz123" },            NeoCoverage{ Name: "abc", Number: "abc123" },        },    }    fmt.Println(coverage)}输出{[{xyz xyz123} {abc abc123}]}这是简要说明;neoCoverage: []NeoCoverage{}代表切片,NeoCoverage该切片应填充NeoCoverage{}元素,如NeoCoverage{ Name: "xyz", Number: "xyz123" }, ...

波斯汪

您还可以省略数组中多余的 Type 声明。以 Alper 的代码库为例。package mainimport "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}]}
随时随地看视频慕课网APP

相关分类

Go
我要回答