Why are receivers pass by value in Go?

后端 未结 3 1115
野趣味
野趣味 2020-12-30 08:02

Seems like you\'d ALWAYS want this:

func (self *Widget) Do() {
}

instead of this

func (self Widget) Do() {
}
3条回答
  •  半阙折子戏
    2020-12-30 08:29

    Sometimes you don't want to pass by reference though. The semantics of

    func (self Widget) Get() Value {
    }
    

    Can be useful if for instance you have a small immutable object. The caller can know for certain that this method doesn't modify it's reciever. They can't know this if the reciever is a pointer without reading the code first.

    To expand on that for instance

    // accessor for things Config
    func (self Thing) GetConfig() *Config {
    }
    

    Just by looking at this method I can know GetConfig is always going to return the same Config. I can modify that config but I can't modify the pointer to Config inside Thing. It's pretty close to a const pointer inside of Thing.

提交回复
热议问题