2

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.

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

3 Comments

That's what I assumed. I was about to edit it and say if you want to initialize with known values, look at @Kavu's answer.
If you want to initialize empty, you're probably doing it wrong. Just leave them nil. The above case isn't empty, though, it's a bunch of zeros. The literal example in the other answer is probably what the user wanted.
Good point, @Dustin. Because he had [2] and [3], I assumed that is what he wanted. Without more info about use case, can't really tell.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.