如何遍历 google.protobuf.ListValue
How to iterate over a 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?
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()
(可能更好,取决于您对值的处理方式)。
我的协议缓冲区规范如下所示:
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?
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()
(可能更好,取决于您对值的处理方式)。