dsdeeaquu38538545 2018-03-30 10:03 采纳率: 100%
浏览 315
已采纳

Go中的'*'和'&'符号是什么意思?

I'm having trouble understanding the * and & symbols in Go. I understand the concept that pointer receivers allow us to modify the value that a receiver points to:

type Vertex struct {
    X, Y float64
}

// This adjust the value of v.X and v.Y
func (v *Vertex) Scale(f float64) {
    v.X = v.X * f
    v.Y = v.Y * f
}

But I also see functions returning the a pointer receiver, for example the net/http library.

func NewRequest(method, url string, body io.Reader) (*Request, error)

In this scenario, why is there a star in front of the Request being returned?

Additionally, I often see & used when assigning variables

import net/http
client := &http.Client{}

Why not just client := http.Client{}?

  • 写回答

3条回答 默认 最新

  • dqh1992 2018-03-30 10:07
    关注

    Have a look here: https://tour.golang.org/moretypes/1

    Go uses pointers like C or C++. The * symbol is used to declare a pointer and to dereference. The & symbol points to the address of the stored value.

    Compared to C/C++, however, the pointer in Go is declared with the * preceding the type rather than following it.

    You can read more about pointers in general here: https://en.wikipedia.org/wiki/Pointer_(computer_programming)

    In your example they are used to pass the address of the instance of the object instead of copying the instance. This is more efficient and you don't have the problem that you have 2 copies objects, because you only need one in this case and would need to destroy one of them.

    This is because the instance of the Object is at a specific address in memory and if you want to refer exactly to that object, you have to pass the address instead of the object itself.

    Some other languages like Java have internal ways to hide the pointer problems from the user or don't use them at all. They often need a garbage collector in that case. Go however lets the user decide to use pointer (though it also has a garbage collector).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型