Search code examples
pointersgocompositionembedding

Pointer difference when initializing embedded structs


I am playing around with struct embedding and have a problem with keeping the same reference to the embedded struct.

Try out Go Playground and see that there are two different pointer addresses to *strings.Reader.

package main

import (
    "fmt"
    "strings"
)

type Base struct {
    reader *strings.Reader
}

func NewBase() *Base {
    r := strings.NewReader("hello")

    fmt.Printf("document: %#+v\n\n", &r)
    return &Base{r}
}

func (b *Base) Check() {
    fmt.Printf("document: %#+v\n\n", &b.reader)

}

type Concrete struct {
    *Base
}

func NewConcrete() *Concrete {
    return &Concrete{NewBase()}
}

func main() {
    c := NewConcrete()
    c.Check()
}

Why are these addresses not the same? How do I fix this?


Solution

  • You're checking the address of the pointer, not the pointer itself.

    func NewBase() *Base {
        r := strings.NewReader("hello")
    
        fmt.Printf("document: %#p\n\n", r)
        return &Base{r}
    }
    
    func (b *Base) Check() {
        fmt.Printf("document: %#p\n\n", b.reader)
    
    }
    

    playground

    //edit

    r := strings.NewReader("hello")
    

    r is a variable holding a pointer to strings.Reader, &r is the address of the variable holding the pointer to strings.Reader.

    fmt.Printf("document: %#+v\n\n", &b.reader)
    

    &b.reader is the address of the variable b.reader, which is holding the pointer of the strings.Reader from earlier.