pointers - 为什么指针上的方法在指针是变量时起作用,而在其他情况下不起作用?

标签 pointers go

运行以下代码时:

package main

import (
    "fmt"
)

type Bar struct {
    name string
}

func (foo Bar) testFunc() {
    fmt.Println(foo.name)
}

func doTest(pointer *Bar) {
    pointer.testFunc() // run `testFunc` on the pointer (even though it expects a value of type `Bar`, not `*Bar`)
}

func main() {
    var baz Bar = Bar{
        name: "Johnny Appleseed",
    }

    doTest(&baz) // send a pointer of `baz` to `doTest()`
}

输出显示为:Johnny Appleseed。我原以为我会在指针上调用 testFunc() 时遇到错误。

之后,我尝试将 doTest(&baz) 换成 &baz.testFunc()。然后我收到错误:

tmp/sandbox667065035/main.go:24: baz.testFunc() used as value

为什么我只在直接调用 baz.testFunc() 而不是通过另一个函数调用时出现错误?不会调用 doTest(&baz)&baz.testFunc() 做完全相同的事情,因为 doTest(pointer *Bar) 只是调用pointer.testFunc()?

Playground 1 (doTest(&baz))

Playground 2 (&baz.testFunc())

最佳答案

这是因为 method values 的自动取消引用

As with selectors, a reference to a non-interface method with a value receiver using a pointer will automatically dereference that pointer: pt.Mv is equivalent to (*pt).Mv.

对于第二行,你有这个错误是因为你获取了 testFunc 的 result 的地址,它没有返回任何值。 您尝试执行的操作如下:

(&baz).testFunc()

按预期工作

关于pointers - 为什么指针上的方法在指针是变量时起作用,而在其他情况下不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41682427/

相关文章:

c - 斐波那契和数组返回

c - 整数指针缓冲区跳过索引

string - 反转字符串范围

go - 如何使用 golang 将 cpu 信息推送到 OpenTSDB 服务器

go - 结构类型不可变

go - 释放结构图

java - 指向结构指针的指针作为 JNA 中的参数

C : reverse array using pointers?

c - Malloc for Structs 的问题

unit-testing - 我怎么知道我在 "go test"内运行