英文:
Filling struct array in golang
问题
我有一个结构体如下:
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",
},
}
请注意,你在填充 Coverage
结构体时,应该使用 neoCoverage
的小写形式。希望这对你有帮助!
英文:
I have struct like
type Coverage struct {
neoCoverage []NeoCoverage
ApocCoverage []ApocCoverage
ApocConfigCoverage []ApocConfigCoverage
}
And
type NeoCoverage struct {
Name string
Number string
}
So how should i fill coverage struct?
Here how I am Trying.
coverage = Coverage{
[]neoCoverage: NeoCoverage{
Name: "xyz",
Number: "xyz123",
},
}
答案1
得分: 8
你可以在数组中省略冗余的类型声明。以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}]}
英文:
You can also omit the redundant Type declarations in the array. Using Alper's code base as example.
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)
}
Output:
{[{xyz xyz123} {abc abc123}]}
答案2
得分: 7
以下是翻译好的内容:
package main
import "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"}, ...
。
英文:
Something like below
package main
import "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)
}
Output
{[{xyz xyz123} {abc abc123}]}
Here is the brief explanation; neoCoverage: []NeoCoverage{}
stands for the slice of NeoCoverage
and that slice should be populated with NeoCoverage{}
elements as in NeoCoverage{ Name: "xyz", Number: "xyz123" }, ...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论