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条)

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记