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 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用