dongyi1996 2017-01-16 18:02
浏览 6
已采纳

为什么当指针是变量时指针上的方法可以工作,但不是呢?

When running the following code:

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()`
}

The output reads: Johnny Appleseed. I would have thought I would have encountered an error for calling testFunc() on a pointer.

After that, I tried switching out doTest(&baz) for &baz.testFunc(). Then I received the error:

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

Why do I only get the error when calling baz.testFunc() directly instead of through another function? Wouldn't calling doTest(&baz) and &baz.testFunc() do the exact same thing, as doTest(pointer *Bar) simply calls pointer.testFunc()?

Playground 1 (doTest(&baz))

Playground 2 (&baz.testFunc())

  • 写回答

1条回答 默认 最新

  • duanlu9816 2017-01-16 18:24
    关注

    It's because of automatic derefencing of 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.

    For the second line, you have this error because you take the address of the result of testFunc which doesn't return any value. What you tried to do is the following:

    (&baz).testFunc()
    

    which works as expected

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答