在proto中使用结构体数组

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

Use Array of struct in proto

问题

我无法调用 gRPC 函数,因为类型不匹配。

我的 proto 文件:

message Analytics {
    // 字段...
}

message AnalyticsSet {
    repeated Analytics analytics = 1;
}

service StatService {
    rpc MyMethod(AnalyticsSet) returns (<something>) {}
}

现在,我需要调用 "MyMethod"。

我的当前代码:

type Analytics struct {
    // 与 proto 文件中的 Analytics 相同的字段
}

analytics := make([]Analytics, 4)

// ... 对 analytics 进行一些修改 ...

_, err := c.MyMethod(context.Background(), analytics)
if err != nil {
    log.Fatalf("error: %s", err)
}

在 Proto 文件中,"AnalyticsSet" 是 "Analytics" 的数组,在 Go 代码中,"analytics" 是类型为 "Analytics" 的数组,但这还不足以调用 "MyMethod",我遇到了类型不匹配的问题。

我应该如何修改 Go 代码?

英文:

I am not able to call a gRPC function due to type mismatch

my proto file :

message Analytics {
    fields ...
}


message AnalyticsSet {
    repeated Analytics analytics = 1;
}

service StatService {
    rpc MyMethod(AnalyticsSet) returns (&lt;something&gt;) {}
}

Now, I need to call "MyMethod"

My current code :

type Analytics struct {
	same fields as in proto : Analytics
}

analytics := make([]Analytics, 4)

// .. some modifications in analytics ...

_, err := c.MyMethod(context.Background(), analytics)
if err != nil {
    log.Fatalf(&quot;error: %s&quot;, err)
}

in Proto file "AnalyticsSet" is the array of "Analytics"
and in Go code "analytics" is an array of type "Analytics"
but this is not enough to call "MyMethod", and I am facing type mismatch..

How should I modify the go code ?

答案1

得分: 1

你必须使用从proto文件生成的Analytics结构体,不能使用自己的类型。

你可以使用protoc和你的.proto文件生成所需的Go代码。下面是一个示例,其中还设置了gRPC生成选项:

$ protoc --go_out=. --go-grpc_out=. --go_opt=paths=source_relative --go-grpc_opt=paths=source_relative analytics.proto

你的proto文件应该设置go_package选项,以描述生成的proto代码所属的Go导入路径。你还需要安装protoc所需的go/go-grpc生成器工具:

$ go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
$ go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest

更多详细信息可以参考以下链接:

英文:

You must use the Analytics struct generated from the proto file -- you cannot use your own type.

You can generate the required Go code using protoc with your .proto file. Here is an example with gRPC generation options set as well:
.

$ protoc --go_out=. --go-grpc_out=. --go_opt=paths=source_relative --go-grpc_opt=paths=source_relative analytics.proto

Your proto file should have the go_package option set to describe the Go import path for that your generated proto code belongs to. You will also need to install the go / go-grpc generator utilities required by protoc:

$ go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
$ go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest

More details can be found in:

huangapple
  • 本文由 发表于 2021年9月22日 17:44:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/69281809.html
匿名

发表评论

匿名网友

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

确定