wfxiang08 / goprotobuf

Automatically exported from code.google.com/p/goprotobuf
Other
0 stars 0 forks source link

Provide MutableFoo() methods which initialize nil fields #33

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
MyMessage.MySubMessage.MyIntField = proto.Int(42)

If you're not careful this can cause a nil dereference, because MySubMessage 
may be nil. Addressing this possibility every place I use this message is 
extremely painful since it's totally obvious what I want: to initialize the 
field with a default value if it's currently nil.

I'd propose the addition of a MutableFoo() method (as in C++), which returns a 
ready-to-go pointer to exactly the thing you're interested in. Then

*MyMessage.MutableMySubMessage().MutableMyIntField() = 42

works with no thought involved.

Any chance of adding these in the compiler?

Original issue reported on code.google.com by y...@hjfreyer.com on 18 Dec 2012 at 2:15

GoogleCodeExporter commented 9 years ago
I think it's pretty unlikely we'll do this. We added getters because
it was a massive pain (and error prone to boot) to deal with fields
with default values. Here, though, it's relatively easy to cope with
nested fields. It's not super-common to be partially constructing
messages, so the best options are using composite literals or doing
the trivial nil checks. Adding MutableFoo helpers would just be a
massive amount of code bloat for relatively little gain.

Original comment by dsymo...@golang.org on 18 Dec 2012 at 11:46

GoogleCodeExporter commented 9 years ago

Original comment by dsymo...@golang.org on 18 Dec 2012 at 11:46