Field naming conventions when field will be exposed by getter

480 views
Skip to first unread message

spiffytech

unread,
Jun 14, 2013, 3:37:31 PM6/14/13
to golan...@googlegroups.com
I have a struct with some fields that get populated by json.Unmarshal. This struct is exposed through an interface; since the struct's fields won't be exposed, I've defined getters for the fields.

Example of what I'm doing: http://play.golang.org/p/OWBof5Yc06

Now I have a conundrum- what should I name the fields? Looking through the standard library, the pattern seems to be getters are simply named like the field would have been, e.g., if I wanted to have a "name" field, my getter should be "Name()". But what do I now call the field? I can't call it "name" because json.Unmarshal can't see it and populate it. I can't call it "Name", because that conflicts with "Name()".

The logical conclusion is my field name should have some prefix or suffix, but I haven't seen anything in the Go docs suggesting what the conventional prefix/suffix would be.

Ryan Leavengood

unread,
Jun 14, 2013, 5:29:43 PM6/14/13
to golan...@googlegroups.com
It seems a bit like a hack, but adding an underscore to the end of capitalized version of the fields (Name_ and Food_) works. 

--
Regards,
Ryan

Aram Hăvărneanu

unread,
Jun 14, 2013, 6:41:59 PM6/14/13
to Ryan Leavengood, golang-nuts
If the struct field is not exported, it's not available for reflection
and json.Unmarshal() can't use it. You can define a custom UnmarshalJSON
function if you need special treatment. You don't even have to
reimplement the functionality yourself, you can create a non-exported
custom type that represents the JSON document. This type would have
exported Fields and would be usable by json.Unmarshal. You'd them
embed this type into your special type and implement UnmarshalJSON
by calling json.Unmarshall.

Here is the revere problem: http://play.golang.org/p/6CQCju_tpL

--
Aram Hăvărneanu

Aram Hăvărneanu

unread,
Jun 14, 2013, 6:50:44 PM6/14/13
to Ryan Leavengood, golang-nuts
> Here is the reverse problem: http://play.golang.org/p/6CQCju_tpL

And here is the complete example: http://play.golang.org/p/53nJr_X8V3

--
Aram Hăvărneanu
Reply all
Reply to author
Forward
0 new messages