在Effective Go中,明确说明,如果一个字段未导出(以小写字母开头),则getter方法应该具有相同的字段名,但以大写字母开头;他们给出的例子是一个字段
我经常遇到需要将字段导出进行JSON编组、与ORM一起使用或其他反射相关目的(如果我没记错,reflect可以读取但不能修改未导出的字段)的情况,因此我的字段需要像上面的例子中那样被称为
有没有一种习惯用法来解决这种情况? 编辑:以下是我遇到的具体问题的示例:
owner
和一个方法Owner
。他们明确建议不要在getter方法名称前使用Get
。我经常遇到需要将字段导出进行JSON编组、与ORM一起使用或其他反射相关目的(如果我没记错,reflect可以读取但不能修改未导出的字段)的情况,因此我的字段需要像上面的例子中那样被称为
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