简体   繁体   中英

Anonymous struct in Protocol Buffer format

Given a Go struct like this:

type House struct {
    Address string
    Rooms []struct {
        Name string
        Windows int
        Doors int
    }
}

Or an equivalent JSON representation:

{
    "address": ""
    "rooms": [
        {
            "name": ""
            "windows": 0
            "doors": 0
        }
    ]
}

What would the equivalent Protocol Buffer representation be?

This is more or less what I would like to do (althought not a valid Proto syntax):

message House {
    string address = 1;
    repeated message {
        string name = 3;
        int32 windows = 4;
        int32 doors = 5;
    } rooms = 2;
}

Instead, doing it like this is valid, but doesn't represent the data accurately since the original rooms slice contains anonymous objects:

message House {
    string address = 1;
    repeated room rooms = 2;
}

message room {
    string name = 1;
    int32 windows = 2;
    int32 doors = 3;
}

Update: I think I misunderstood how the message declaration works. The second example I gave should be sufficient and actually does not interfere with JSON unmarshalling.

In order to achieve what you want and get rid of anonymous structs, I think you should declare room message within House and then assign it as repeated, something like this:

message House {
  message room {
    string name = 1;
    int32 windows = 2;
    int32 doors = 3;        
  }
  string address = 1;
  repeated room rooms = 2;
}

It will correspond to the following structs in go:

type House struct {
    name         string                     
    rooms       []*room
}

type room struct {
    name string
    windows int32
    doors int32
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM