dongyiyu882684 2015-03-24 10:55
浏览 16
已采纳

Go语言中的结构指针

this is my code:

package main
import ("fmt")

type Message struct {

    Text []byte
    Tag string
}

func main() {

    var m Message

    pkt := []byte("Hey")
    editMessage(&m, &pkt)

    fmt.Println(string(m.Text))
    }

func editMessage(m *Message, pkt *[]byte) {

    m.Text = *pkt
}

And I get "Hey" as expected on the output.

If I change m.Text = *pkt with (*m).Text = *pkt It works as well!

Which is the correct/more efficient version? Or is it just a shortcut?

This thing doesn't now work all the time, if I use

c *net.Conn

as input in a function, I must use

something := (*c).RemoteAddr()  

to get it working.

Thank you

  • 写回答

1条回答 默认 最新

  • dousu1900 2015-03-24 11:04
    关注

    If you refer to the Golang Language Specification - Method values section, you'll note this quote (emphasis mine):

    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.

    Thus, your pointer is being automatically dereferenced for you.

    net.Conn is an interface .. and as such, you must manually dereference the pointer in order for this to work.

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

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分