运行以下代码时:
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()
?
最佳答案
这是因为 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/