当指针是变量时,为什么指针上的方法有效?

时间:2017-01-16 18:02:55

标签: 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())

1 个答案:

答案 0 :(得分:2)

这是因为method values

的自动解散
  

与选择器一样,使用指针对带有值接收器的非接口方法的引用将自动取消引用该指针:pt.Mv等效于(* pt).Mv。

对于第二行,您有此错误,因为您获取了testFunc的结果的地址,该地址不返回任何值。 您尝试做的是以下内容:

(&baz).testFunc()

按预期工作