登录
首页 >  Golang >  Go问答

如何不为每个原始结构重复相同的字段?

来源:stackoverflow

时间:2024-04-11 09:42:35 435浏览 收藏

亲爱的编程学习爱好者,如果你点开了这篇文章,说明你对《如何不为每个原始结构重复相同的字段?》很感兴趣。本篇文章就来给大家详细解析一下,主要介绍一下,希望所有认真读完的童鞋们,都有实质性的提高。

问题内容

我第一次使用 protobuf .proto 文件。

我有许多具有相同字段的模型:

message player {
  uint64 id = 1;
  google.protobuf.timestamp createdat = 2;
  google.protobuf.timestamp updatedat = 3;
  string firstname = 4;
  string lastname = 5;
  //...
}
message team {
  uint64 id = 1;
  google.protobuf.timestamp createdat = 2;
  google.protobuf.timestamp updatedat = 3;
  string name = 4;
  //...
}
message League {
  uint64 id = 1;
  google.protobuf.Timestamp createdAt = 2;
  google.protobuf.Timestamp updatedAt = 3;
  string name = 4;
  //...
}

...以及许多其他...

如您所见,我在每个结构中重复了相同的字段

在这种情况下,dry(不要重复)的最佳做法是什么?

我正在使用 golang。

我可以像 go 语言一样嵌入它们吗?


正确答案


您可以使用公共字段创建消息:

message Meta {
  uint64 id=1;
  google.protobuf.Timestamp createdAt = 2;
  google.protobuf.Timestamp updatedAt = 3;
}

message Player {
  Meta meta=1;
  string firstname = 4;
  string lastname = 5;
  //...
}

message Team {
  Meta id = 1;
  string name = 2;
  //...
}
message League {
  Meta meta=1;
  string name = 2;
  //...
}

今天关于《如何不为每个原始结构重复相同的字段?》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>