gpt4 book ai didi

go - 如何迭代 google.protobuf.ListValue

转载 作者:行者123 更新时间:2023-12-01 22:10:38 29 4
gpt4 key购买 nike

我的 Protocol Buffer 规范如下所示:

message CreateContextRequest {
map<string, google.protobuf.ListValue> my_mapping = 2;
}
我使用此 Protocol Buffer 的 Go 代码如下所示:
1:   fmt.Println("protocBuff = ", protocBuff);
2: fmt.Println("protocBuff.MyMapping = ", protocBuff.MyMapping);
3: for myKey, myListValue := range protocBuff.MyMapping {
4: fmt.Println("myKey:", myKey, "=>", "myListValue:", myListValue)
5: for _, element := range myListValue {
6: fmt.Printf("element = ", element)
7: }
8: }
第 1-4 行工作正常。但是第 5 行给出了这个编译时错误: cannot range over myListValue (type *structpb.ListValue)那么如何迭代 myListValue 呢?

最佳答案

ListValue的定义(删除了私有(private)字段)是:

type ListValue struct {
// Repeated field of dynamically typed values.
Values []*Value `protobuf:"bytes,1,rep,name=values,proto3" json:"values,omitempty"`
}
因此,要遍历它,您可以使用:
  • for _, element := range myListValue.Values
  • for _, element := range myListValue.GetValues() (更安全,因为它会检查 nil myListValue )
  • for _, element := range myListValue.AsSlice() (可能会更好,取决于您对这些值所做的事情)。
  • 关于go - 如何迭代 google.protobuf.ListValue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63945927/

    29 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com