type person struct{
Name string
Age int
}
// parameters : (pointer to person struct), which is basically address of person object
func printPerson(p *person) {
// when we add '*' to a address, then it becomes dereferencing, Hence
// I read "*p.Name" as "person object dot Name" and i expect it to give value,
// I get this error:
// ./prog.go:20:15: invalid indirect of p.Name (type string)
// ./prog.go:20:24: invalid indirect of p.Age (type int)
fmt.Println(*p.Name, *p.Age) // does not works, ERROR THROWN
// But this works perfectly
// I read it as "person address dot name and person address dot age"
// for me it does not make sense when we say "address dot field name",
// shouldn't it be "object dot field name ? "
fmt.Println(p.Name, p.Age)
}
func main() {
p := person{"foobar", 23}
printPerson(&p) // we are sending address to the method
}
为什么我们不能执行取消引用的对象点字段名而不是地址点字段名?请阅读代码注释以获取问题解释,我在这里缺少什么?
最佳答案
p.Name
和 p.Age
按原样工作,因为如果 p
是指向结构的指针,那么 p.Name
是 (*p).Name
的简写。引自 Spec: Selectors:
In the expression
x.f
[...] if the type ofx
is a defined pointer type and(*x).f
is a valid selector expression denoting a field (but not a method),x.f
is shorthand for(*x).f
.
鉴于此,*p.Name
不会尝试取消引用 p
并引用 Name
字段,它会尝试取消引用不是指针的 p.Name
字段。
如果您使用括号来对间接寻址进行分组,它会起作用:
fmt.Println((*p).Name, (*p).Age)
但同样,由于这种形式非常常见,规范允许您省略指针间接寻址并简单地编写 p.Name
。
关于go - 为什么在地址上取消引用会在 golang 中产生 "invalid indirect"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66796321/