Search code examples
pointersgogetter-setter

Copying or passing the pointer


I've seen recommendations to use the following in getters and setters, i.e. pass a pointer when you are setting the value in order to change the original data, but it's not required when getting the value.

In the case of a getter, without a pointer, the value is copied. My question is, isn't it inefficient to copy the object to get value out of it, could we not use a pointer as well?

type Foo struct {
     Body string
}

func (foo Foo) GetBody() interface{} {
    return foo.Body
}

func (foo * Foo) SetBody(body string) {
    foo.Body = body
}

Solution

  • Where did you see a recommendation to use a non-pointer receiver for getters ? I don’t think this is done in the official packages; e.g., the zip package definitely uses pointer receivers for both getters and setters.

    func (h *FileHeader) ModTime() time.Time
    func (h *FileHeader) Mode() (mode os.FileMode)
    func (h *FileHeader) SetModTime(t time.Time)
    func (h *FileHeader) SetMode(mode os.FileMode)
    

    See also :