首页 > 解决方案 > 如何迭代 google.protobuf.ListValue

问题描述

我的协议缓冲区规范如下所示:

message CreateContextRequest {
  map<string, google.protobuf.ListValue> my_mapping = 2;
}

我使用此协议缓冲区的 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 呢?

标签: goiterationprotocol-buffersgrpc

解决方案


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

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()(可能会更好,取决于您对这些值所做的事情)。

推荐阅读