Dan LaManna
Dan LaManna

Reputation: 3501

Understanding Go Pointers

I expect this code to produce 4 addresses, 2 for each node, thus, having 2 identical addresses, and then another set of 2 identical addresses:

type node struct {
    identifier string
    parent     *node
    children   []*node
    root       int
}

func visitNodes(root *node) {   
    for i := 0; i < len(root.children); i++ {
        fmt.Printf("Visiting node %s\n", &root.children[i])
        printNodeAddress(root.children[i])
    }
}

func printNodeAddress(node *node) {
    fmt.Println(&node)
}


func main() {
    root := new(node)
    node1 := new(node)
    node2 := new(node)

    root.children = append(root.children, node1)
    root.children = append(root.children, node2)

    visitNodes(root)
}

Produces:

Visiting node  %!s(**main.node=0x10500170)
0x10500180
Visiting node  %!s(**main.node=0x10500174)
0x10500190

While I expect it to produce something like this:

Visiting node  %!s(**main.node=0x10500170)
0x10500170
Visiting node  %!s(**main.node=0x10500174)
0x10500174

Am I misunderstanding the fundamentals of go pointers, or is different when dealing with slices?

Upvotes: 2

Views: 168

Answers (1)

Caleb
Caleb

Reputation: 9458

The issue is that you're taking the address of a pointer:

func printNodeAddress(node *node) {
    fmt.Println(&node) // there's now a second layer of indirection in here. a **node
}

When really what you're trying to see is the pointer's memory address. You should change your Printf to this:

fmt.Printf("Visiting node %p\n", root.children[i])

And your printNodeAddress function to this:

fmt.Printf("%p\n", node)

Then you'll get this:

Visiting node 0x1052f2c0
0x1052f2c0
Visiting node 0x1052f2e0
0x1052f2e0

Upvotes: 5

Related Questions