pointers - Golang 自动引用,并不总是可以获得值的地址

标签 pointers go types reference

我是 Golang 世界的新手。我试图理解自动引用的概念。

我对以下程序感到困惑?第一个和第二个有什么区别

  1. main 函数的第一行
age(20).print()
  • 第二行和第三行
  • myAge := age(20)
    myAge.print()
    

    完整程序如下:

    package main
    import "fmt"
    
    type age uint8
    
    func (a *age) print() {
      fmt.Println(a)
    }
    
    
    func main() {
      age(20).print() // this line throws error
    
      // however, the below line works properly
      myAge := age(20)
      myAge.print()
    }
    

    请帮助理解这两种方法之间的区别。我假设它们都是相同的。

    最佳答案

    这是编译器提供的便利。正如 calls 中提到的规范部分:

    If x is addressable and &x's method set contains m, x.m() is shorthand for (&x).m()

    这在 method Pointers vs Values 中有详细阐述。有效执行部分。

    要确定什么是可寻址的,您可以引用Address operators规范部分。具体来说:

    ... either a variable, pointer indirection, or slice indexing operation; or a field selector of an addressable struct operand; or an array indexing operation of an addressable array. As an exception to the addressability requirement, x may also be a (possibly parenthesized) composite literal.

    回到你的例子,(a *age) print()age 上的指针接收器。这意味着对 age 的完整调用变量是 &<expr>.print() 。这只能在 expr 时完成。是可寻址的。查看可寻址性要求:

    • myAge是一个变量,它是可寻址的。
    • age(20)是类型转换并且不可寻址。

    忽略方法调用,您可以通过尝试以下操作轻松检查可寻址性:

    _ = &age(20)     // cannot take the address of age(20)
    myAge := age(20)
    _ = &myAge       // works fine
    

    关于pointers - Golang 自动引用,并不总是可以获得值的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62589461/

    相关文章:

    c - C 中的段错误导致代码有时运行但有时不运行

    mysql - golang sql.open() 期望 0 个参数得到 1

    java - 为什么我无法在此 VectorQueue 实例上实现我的 Vector 方法?

    c - 结构体和指针

    c - 我如何将 const 指针发送到 c 中的非 const 指针?

    go - sync.Map 是原子的吗?我主要是指加载、存储、加载或存储、删除

    multithreading - 可能/推荐在 Go 中编写事件驱动的应用程序?

    typescript - 创建函数类型(TypeScript 接口(interface))

    java - Scala 的 .type 和 Java 的 .class 字面量

    c++ - this->field 与 C++ 中的 this.field