在Effective Go中,它是clearly stated,在字段未導出的情況下(以小寫字母開頭),getter方法應具有相同的字段名稱,但應以大寫字母開頭;他們給出的例子是作爲字段的owner
和作爲方法的Owner
。他們明確建議不要在獲取方法名稱前面使用Get
。Go Getter方法vs字段,正確命名
我經常遇到需要將字段導出爲JSON封送,與ORM一起使用或與其他反射相關的目的(IIRC反射可以讀取但不能修改未導出的字段)的情況,所以我的字段需要被調用在上面的例子中爲Owner
,因此不能有一個Owner
方法。
有沒有一種習慣的命名方式來解決這種情況?
編輯:這裏是我遇到的一個具體的例子:
type User struct {
Username string `db:"username" json:"username"`
// ...
}
// code in this package needs to do json.Unmarshal(b, &user), etc.
。
// BUT, I want code in other packages to isolate themselves from
// the specifics of the User struct - they don't know how it's
// implemented, only that it has a Username field. i.e.
package somethingelse
type User interface {
Username() string
}
// the rest of the code in this other package works against the
// interface and is not aware of the struct directly - by design,
// because it's important that it can be changed out without
// affecting this code
只需使用「獲取」前綴即可。這就是[Go protobuf generator](https://github.com/golang/protobuf)所做的。 –
@TimCooper我聽到你的聲音,但我幾乎寧願打亂字段名稱,因爲接口方法名稱會出現在更多的地方(並在更多的包中使用),對於直觀和習慣用法來說更重要。 –
如果導出字段,爲什麼要使用Getter/Setter?這只是讓界面更容易混淆,通過允許多種方式來完成同樣的事情。 – Flimzy