简体   繁体   中英

Golang - Slices in nested structs

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 .

It's possible with []int{1,2,3} notation, example (solves your problem):

&tar{foo: foo{bar: bar{v1: []int{2}, v2: []int{2}}}}

PS I strongly advise you to read The Go Programming Language Specification and FAQ section .

v1 and v2 are slices. The way you initialize those is with make([]int, YOUR_INITIAL_SIZE) instead of [2] and [3] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM