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条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效