How to set and get fields in struct's method

后端 未结 3 859
故里飘歌
故里飘歌 2020-11-27 03:02

After creating a struct like this:

type Foo struct {
    name string
}

func (f Foo) SetName(name string) {
    f.name = name
}

func (f Foo) GetName() strin         


        
3条回答
  •  無奈伤痛
    2020-11-27 03:24

    Setters and getters are not that idiomatic to Go. Especially the getter for a field x is not named GetX but just X. See http://golang.org/doc/effective_go.html#Getters

    If the setter does not provide special logic, e.g. validation logic, there is nothing wrong with exporting the field and neither providing a setter nor a getter method. (This just feels wrong for someone with a Java background. But it is not.)

提交回复
热议问题