go - 为什么在地址上取消引用会在 golang 中产生 "invalid indirect"错误

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.Namep.Age 按原样工作,因为如果 p 是指向结构的指针,那么 p.Name(*p).Name 的简写。引自 Spec: Selectors:

In the expression x.f [...] if the type of x 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/

相关文章:

delphi - GDI+ DrawLine 什么都不画

python-3.x - 根据索引和标签转换数据框

r - 如何在 Apple Silicon (M1) Mac 上安装 RcppArmadillo

c - 这个 C 函数是什么意思?函数指针?

ios - SwiftUI:如何知道修饰符的正确顺序?

qt - 如何将 QML 文件组织到嵌套文件夹中?

ios - 如何将十六进制数据分解为来自 BLE 设备的可用数据? (速度和节奏)

heroku - Unresolved 导入 `core::task::Wake`

firebase - 在 Flutter 中使用相同的 Firebase 将同一应用程序中的用户和卖

c# - 添加新包会破坏 .NET 5 应用程序