Go Getter Methods vs Fields, Proper Naming

Viewed 5540

In Effective Go, it's clearly stated that in the case where a field is unexported (begins with a lower case letter) a getter method should have the same field name but starting with upper case; the example they give is a owner as a field and Owner as a method. And they explicitly advise against using Get in front of the getter method name.

I frequently encounter situations where I need the field to be exported for JSON marshaling, use with an ORM, or other reflection related purposes (IIRC reflect can read but not modify unexported fields), so my field would need to be called Owner in the example above and thus cannot have an Owner method.

Is there an idiomatic way of naming which addresses this situation?

EDIT: Here's a concrete example of what I'm running into:

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
2 Answers
Related