0

I am having a problem figuring out how to reference elements of a sub structure.

See: http://play.golang.org/p/pamS_ZY01s

Given something like following.... How do you reference data in the room struct? I have tried fmt.Println(*n.Homes[0].Rooms[0].Size), but that does not work.

Begin Code example

package main

import (
    "fmt"
)

type Neighborhood struct {
    Name  string
    Homes *[]Home
}

type Home struct {
    Color string
    Rooms *[]Room
}

type Room struct {
    Size string
}

func main() {
    var n Neighborhood
    var h1 Home
    var r1 Room

    n.Name = "Mountain Village"
    h1.Color = "Blue"
    r1.Size = "200 sq feet"

    // Initiaize Array of Homes
    homeslice := make([]Home, 0)
    n.Homes = &homeslice

    roomslice := make([]Room, 0)
    h1.Rooms = &roomslice

    *h1.Rooms = append(*h1.Rooms, r1)
    *n.Homes = append(*n.Homes, h1)

    fmt.Println(n)
    fmt.Println(*n.Homes)

}

1 Answer 1

4

First, *[]Home is really wasteful. A slice is a three worded struct under the hood, one of them being itself a pointer to an array. You are introducing a double indirection there. This article on data structures in Go is very useful.

Now, because of this indirection, you need to put the dereference operator * in every pointer-to-slice expression. Like this:

fmt.Println((*(*n.Homes)[0].Rooms)[0].Size)

But, really, just take out the pointers.

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

3 Comments

Thanks, the reason for the pointer is because I will be marshal-ing the data in to JSON and that is how Andrew Gerrand from Google told me to do it so I do not have empty elements showing up in the JSON data.
And that's true for non-reference Go types, e. g. for mapping JSON objects to structs, or JSON numbers to ints. But slices themselves can be nil, represented as null. play.golang.org/p/psN_WIcCo4
Great. I now understand Andrew's comments better... Thanks for all of your feedback. This really helps me.

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.