douzoudang1511 2018-08-08 08:41
浏览 110
已采纳

使用协议缓冲区错误进行构建:结构初始化程序中的值太少

I have a proto file:

syntax = "proto3";

package main;

message Client {
    int32 Id = 1;
    string Name = 2;
    string Email = 3;
}

The compiled Client struct like below:

type Client struct {
    Id                   int32    `protobuf:"varint,1,opt,name=Id,proto3" json:"Id,omitempty"`
    Name                 string   `protobuf:"bytes,2,opt,name=Name,proto3" json:"Name,omitempty"`
    Email                string   `protobuf:"bytes,3,opt,name=Email,proto3" json:"Email,omitempty"`
    XXX_NoUnkeyedLiteral struct{} `json:"-"`
    XXX_unrecognized     []byte   `json:"-"`
    XXX_sizecache        int32    `json:"-"`
}

When I am trying to init this Client struct like below:

client := &Client{123, "John", "john@aol.com"}

I am getting building error: too few values in struct initializer. I found a way to fix it by adding XXX_NoUnkeyedLiteral, XXX_unrecognized, XXX_sizecache. I don't know what these are, and wondering if this is the right way to do it:

client := &Client{123, "John", "john@aol.com", struct{}{}, []byte{}, int32(0)}
  • 写回答

2条回答 默认 最新

  • duanjiu2701 2018-08-08 09:03
    关注

    In struct composite literals you may omit the field names to which you list values for (this is called unkeyed literal), but then you have to list initial values for all fields and in their declaration order. Or you may use a keyed literal where you explicitly state which fields you specify initial values for. In the latter, you are allowed to omit any of the fields, you may just list the ones you want to give an initial value different from the field's zero value).

    You used unkeyed composite literal, in which case you must list values for all fields, which you didn't. This is what the error message tells you: "too few values in struct initializer".

    The field name (generated by protobuf) itself should give you the hint: XXX_NoUnkeyedLiteral. It suggests you should not use a composite literal without keys.

    So use a composite literal with keys, like this::

    client := &Client{
        Id:    123,
        Name:  "John",
        Email: "john@aol.com",
    }
    

    This form is more readable, and it is immune to struct changes. E.g. if the Client struct would get new fields, or fields would get rearranged, this code would still be valid and compile.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵