如何重用不同消息类型的字段?

问题描述

这是.proto文件内容

Syntax="proto3";

package topic;

option go_package="github.com/mrdulin/grpc-go-cnode/internal/protobufs/topic";

import "internal/protobufs/shared/user.proto";
import "internal/protobufs/reply/domain.proto";

enum Tab {
  share = 0;
  ask = 1;
  good = 2;
  job = 3;
}

message Topic {
  string id = 1;
  string author_id = 2;
  Tab tab = 3;
  string title = 4;
  string content = 5;
  shared.UserBase author = 6;
  bool good = 7;
  bool top = 8;
  int32 reply_count = 9;
  int32 visit_count = 10;
  string create_at = 11;
  string last_reply_at = 12;
}

message TopicDetail {
  string id = 1;
  string author_id = 2;
  Tab tab = 3;
  string title = 4;
  string content = 5;
  shared.UserBase author = 6;
  bool good = 7;
  bool top = 8;
  int32 reply_count = 9;
  int32 visit_count = 10;
  string create_at = 11;
  string last_reply_at = 12;
  // different fields
  repeated reply.Reply replies = 13;
  bool is_collect = 14;
}

如您所见,在TopicTopicDetail消息类型中,大多数字段是相同的。有什么办法可以继承,合成(嵌入的消息类型),以便我进行干燥?

解决方法

当然,您可以执行以下操作:

message Topic {
  string id = 1;
  string author_id = 2;
  Tab tab = 3;
  string title = 4;
  string content = 5;
  shared.UserBase author = 6;
  bool good = 7;
  bool top = 8;
  int32 reply_count = 9;
  int32 visit_count = 10;
  string create_at = 11;
  string last_reply_at = 12;
}

message TopicDetail {
  Topic topic = 1;
  repeated reply.Reply replies = 2;
  bool is_collect = 3;
}

有关详细信息,您可以检查https://developers.google.com/protocol-buffers/docs/proto3#other,或者如果您想将它们嵌套,也可以这样做,请参见:https://developers.google.com/protocol-buffers/docs/proto3#nested