如何在protobuf语言中表示golang的”any”类型

huangapple go评论94阅读模式
英文:

How to represent golang "any" type in protobuf language

问题

我正在使用一个protobuf定义文件来创建golang类。

file.proto

message my_message {
 <使用什么类型?> data = 1 [json_name = "data"]
}

generated.go

type MyMessage struct {
  data any
}

我已经查看了StructValueAny,但在生成的类中,它们都没有将类型标记为"any"。

我找到的最接近的是Value类型,它可以容纳原始类型、结构体和列表。

英文:

am using a protobuf definition file to create golang classes

file.proto

message my_message {
 <what type to use?> data = 1 [json_name = "data"]
}

generated.go

type MyMessage struct {
  data any
}

I have checked out Struct , Value and Any, though none of them actually mark the type as “any” in generated classes.

The closes I get is Value type which can accomodate primitives as well as structs and lists.

答案1

得分: 1

据我所知,Go代码生成器在生成字段时不会使用any/interface{}。在这里,你可能想要使用google.protobuf.Any,但是生成的代码中的字段类型将是anypb.Any。如果你确实需要使用any类型,那么不幸的是你将不得不手动映射到另一个结构体。

英文:

As far as I'm aware the Go code generator doesn't have any circumstances where any/interface{} will be used for a generated field.

google.protobuf.Any is likely what you want here, but the field in the generated code will of type anypb.Any. If you absolutely require the any type be used, you'll unfortunately have to manually map to another struct.

huangapple
  • 本文由 发表于 2023年2月15日 18:54:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/75458732.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定