Golang – 嵌套结构体中的切片

huangapple go评论100阅读模式
英文:

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}}}}

附注:我强烈建议你阅读Go编程语言规范常见问题解答部分

英文:

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

v1v2是切片。你初始化它们的方式是使用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].

huangapple
  • 本文由 发表于 2014年2月24日 03:32:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/21973390.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定