go - 如何迭代 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()
(可能会更好,取决于您对这些值所做的事情)。
推荐阅读
- python-3.x - 升级到更强大的新笔记本电脑后,pymc3 运行非常缓慢
- bash - 尝试在 mac 上的 bash 脚本中运行 chrome 时出现问题
- r - 在分组数据中,如何仅按列的值排列 *some* 列的行,同时保持其余列不变?
- javascript - 为什么我尝试连接时无法访问 http 服务器
- c# - 运行读取时带有 IronOcr 的 PDF Ocr 抛出 SEHException
- javascript - 是否可以操作 Array.prototype.map() 的索引参数?
- css - CSS过渡变换旋转错误
- java - 如何为java中的值数组设置特定的色调(逐渐变暗)?
- angular - 对象太大而无法检查。打开浏览器控制台查看?
- firebase - 尝试更新您的 pubspec.yaml 以将最小 SDK 约束设置为 2.2.2 或更高版本,然后运行“pub get”