pointers - Go 在哪里定义 p.Field(与 (*p).Field 相对)是有效语法,即使 p 是指向结构的指针?

标签 pointers go syntax

这是我的 Go 程序。

package main

import (
    "fmt"
)

type Person struct {
    Name string
}

func main() {
    p := &Person{"Jack"}

    // The following statement makes sense. We dereference the
    // pointer to reach the Person object and then retrieve its Name
    // field.
    fmt.Println((*p).Name)

    // But the following statement does not make sense. How does
    // this code work by retrieving the Name field directly from the
    // pointer without dereferencing it?
    fmt.Println(p.Name)
}

这是输出。

$ go run foo.go 
Jack
Jack

p*Person 类型时,即指向 Person 的指针,如何访问其字段 Name 是合法的 没有取消引用它?我看到所有使用语法 p.Name 而不是 (*p).Name 的 Go 教程,但 Go 语言确切地定义了 p.Person作为合法语法?

最佳答案

Spec: Selectors:

The following rules apply to selectors:

[...] if the type of x is a named pointer type and (*x).f is a valid selector expression denoting a field (but not a method), x.f is shorthand for (*x).f.

语言规范帮助您使用指针语法,让您感觉在某些情况下您甚至没有使用指针。取消引用指针以访问其字段就是其中之一。如果它们是可寻址的,您也可以调用在非指针值上具有指针接收器的方法,参见 Calling a method with a pointer receiver by an object instead of a pointer to it?

您还可以对数组指针进行索引和 slice ,例如如果 a 是指向数组类型的指针:

  • a[x](*a)[x]
  • 的简写
  • a[low : high](*a)[low : high]的简写。

关于pointers - Go 在哪里定义 p.Field(与 (*p).Field 相对)是有效语法,即使 p 是指向结构的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43729893/

相关文章:

mysql - CREATE TABLE 中的 1064 错误 ... TYPE=MYISAM

pointers - 使用 xlsx 包 panic : runtime error: invalid memory address or nil pointer dereference Go

C:指针算术的评估:操作何时完成?

C - 指针释放后不为空

go - 当变量已经声明时,为什么我必须将类型传递给 make 函数?

database - Gorm 只返回一个而不是多个结果

go - 如何为 []map[string]string 添加示例

JavaScript 空格语法错误

c++ - 为什么我不能通过 const 指针修改变量?

c - 在 C 中使用指向函数的指针调用函数