jarvis657 / goprotobuf

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

Default value for nested messages #46

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
--- 8< create_organization.proto --------------------------
package com.service.create_organization;

import "common/common.proto";

message Request {
        required common.OrganizationProfile organization = 2;
}
-------------------------------------------------------

--- 8< common.proto------------------------------------

package com.service.common;

message OrganizationProfile {
         required string status = 1;
         required string name = 2;
}
-------------------------------------------------------

--- 8< create_organization.pb.go 
--------------------------------------------------------------------------------
---------
func (m *Request) GetOrganization() 
*com_hailocab_service_h4b_organization_common.OrganizationProfile {
        if m != nil {
                return m.Organization
        }
        return nil
}

type Request struct {
        Organization     *com_service_common.OrganizationProfile `protobuf:"bytes,2,req,name=organization" json:"organization,omitempty"`
        XXX_unrecognized []byte                                                            `json:"-"`
}
--------------------------------------------------------------------------------
--------------------------------------

This means that a message of type `create_organization' initialized with 
default value, contains a `nil' organization field. Is this the intended 
behaviour? Because given the description in the README about the handling of 
default values, that means that even the organization field and its nested 
fields are required, you can easily end up with a nil pointer and you need to 
do this repetitive nil checking in each place where you handle this type of 
messages.

Original issue reported on code.google.com by ricardo....@hailocab.com on 14 Nov 2013 at 5:44

GoogleCodeExporter commented 9 years ago
Messages don't have default values per se. What you are noticing is just the 
standard Go zero type for a struct, which has all the fields set to their zero 
type (and a pointer's zero type is nil).

The getter methods explicitly handle nil receivers to make this easier to use. 
You can call req.GetOrganization().GetName() to get the default value of the 
name field even if req is a nil *Request.

Original comment by dsymo...@golang.org on 14 Nov 2013 at 9:32

GoogleCodeExporter commented 9 years ago
Oh, I was missing that. Makes sense. Thanks!

Original comment by ricardo....@hailocab.com on 15 Nov 2013 at 10:31