英文:
Golang - Slices in nested structs
问题
我有一个深度嵌套的结构体,其中包含两个切片,如下所示:
package main
import "fmt"
type bar struct {
v1 []int
v2 []int
}
type foo struct{ bar bar }
type tar struct{ foo foo }
func main() {
f := &tar{foo: foo{bar: bar{v1: make([]int, 2), v2: make([]int, 3)}}}
fmt.Printf("Hello, playground %s", f)
}
如何初始化这两个切片?或者如何使这段代码工作?
这是它的 Golang Play 链接:http://play.golang.org/p/zLutROI4YH。
英文:
I have a deeply nested struct which contains two slices, as seen below:
package main
import "fmt"
type bar struct {
v1 []int
v2 []int
}
type foo struct{ bar bar }
type tar struct{ foo foo }
func main() {
f := &tar{foo: foo{bar: bar{v1: [2], v2: [3]}}}
fmt.Printf("Hello, playground %s", f)
}
How do I initialize the two slices? Or how do I get this code working?
Here is the Golang Play for it: http://play.golang.org/p/zLutROI4YH.
答案1
得分: 7
可以使用[]int{1,2,3}
的表示方法来实现,例如(解决你的问题):
&tar{foo: foo{bar: bar{v1: []int{2}, v2: []int{2}}}}
英文:
It's possible with []int{1,2,3}
notation, example (solves your problem):
&tar{foo: foo{bar: bar{v1: []int{2}, v2: []int{2}}}}
P.S. I strongly advise you to read The Go Programming Language Specification and FAQ section.
答案2
得分: 1
v1
和v2
是切片。你初始化它们的方式是使用make([]int, YOUR_INITIAL_SIZE)
,而不是[2]
和[3]
。
英文:
v1
and v2
are slices. The way you initialize those is with make([]int, YOUR_INITIAL_SIZE)
instead of [2]
and [3]
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论