简体   繁体   English

协议缓冲区格式的匿名结构

[英]Anonymous struct in Protocol Buffer format

Given a Go struct like this: 给定这样的Go结构:

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

Or an equivalent JSON representation: 或等效的JSON表示形式:

{
    "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): 这或多或少是我想做的(虽然不是有效的Proto语法):

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: 相反,这样做是有效的,但由于原始rooms切片包含匿名对象,因此不能准确表示数据:

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. 我给出的第二个示例应该足够,并且实际上不会干扰JSON解组。

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: 为了实现所需的功能并摆脱匿名结构,我认为您应该在House中声明房间消息,然后将其分配为重复消息,如下所示:

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: 它将与go中的以下结构相对应:

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

type room struct {
    name string
    windows int32
    doors int32
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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