2

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?

1 Answer 1

3

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.

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

Comments

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.