初始化嵌套结构时的指针差异

huangapple go评论84阅读模式
英文:

Pointer difference when initializing embedded structs

问题

我正在玩嵌入结构体的代码,并且在保持对嵌入结构体的相同引用方面遇到了问题。

请尝试使用Go Playground查看*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()
}

为什么这些地址不相同?我该如何解决这个问题?

英文:

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

得分: 3

你正在检查指针的地址,而不是指针本身。

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)

}

r 是一个变量,保存了指向 strings.Reader 的指针,&r 是保存指向 strings.Reader 的指针的变量的地址。

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

&b.reader 是变量 b.reader 的地址,它保存了之前的 strings.Reader 的指针。

英文:

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)

}

<kbd>playground</kbd>

//edit

r := strings.NewReader(&quot;hello&quot;)

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

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

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

huangapple
  • 本文由 发表于 2014年8月11日 02:13:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/25231592.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定