在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