英文:
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)
}
//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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论