2018-03-30 10:03 阅读 204


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{}?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    dqh1992 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).

    点赞 评论 复制链接分享
  • duangan4406 duangan4406 2018-03-30 10:10

    * is used to dereference a pointer and & is used to get the address of a value. Take a look at Golang Tour Where as Request is a struct in http package:

    type Request struct {}

    *Request is returned as pointer to the struct in below code:

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

    You should checkout the resource for request.go here https://golang.org/src/net/http/request.go.

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

    We use & address operator with client to set the values of struct to change values of Client struct. If we don't take the address It will create a copy of the struct rather using the original one.

    Go through Client struct to have an idea of fields

    点赞 评论 复制链接分享