Pointers 为什么指针上的方法在指针是变量的情况下工作,而不是其他情况?
运行以下代码时:Pointers 为什么指针上的方法在指针是变量的情况下工作,而不是其他情况?,pointers,go,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 v
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()
时会遇到错误
在那之后,我尝试为和baz.testFunc()切换doTest(&baz)
。然后我收到了错误:
tmp/sandbox667065035/main.go:24: baz.testFunc() used as value
为什么我只在直接调用baz.testFunc()
而不是通过另一个函数调用时才会出现错误?调用doTest(&baz)
和&baz.testFunc()
不会做与doTest(指针*Bar)
只调用指针.testFunc()
完全相同的事情吗
这是因为
与选择器一样,对使用指针的值接收器的非接口方法的引用将自动取消对该指针的引用:pt.Mv相当于(*pt.Mv)
对于第二行,您有这个错误,因为您获取testFunc的结果的地址,该地址不返回任何值。
您尝试执行以下操作:
(&baz).testFunc()
正常工作Go具有自动指针解引用和(点)调用。