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 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?