首页 > 解决方案 > 如何在 Golang protobuf v3 结构中获取 time.Time?

问题描述

我现在github.com/golang/protobuf/ptypes/timestamp在 protobuf 消息文件中使用 google time 包。

google.protobuf.Timestamp UpdateTime = 9;

但是该UpdateTime属性*timestamp.Timestamp在protoc编译后成为golang struct中的指针,它不是a time.Time,我无法将这些属性保存到Mysql时间戳列中。

我能做些什么?

标签: mysqlgotimestampprotocol-buffers

解决方案


time.Time要从type 的 protobuf 字段中获取 a google.protobuf.Timestamp,请使用在该类型上定义的AsTime方法timestamppb.Timestamp

在您的数据库或任何其他需要 a 的位置生成插入调用time.Time时,调用myMsg.UpdateTime.AsTime()以获取所需的值(其中myMsg是相关 Protobuf 消息类型实例的变量)。


此答案假定您正在使用包中定义的新 Protobuf APIv2 接口,google.golang.org/protobuf或者您正在使用 APIv1 的 APIv2 兼容实现,github.com/golang/protobuf在版本v1.20或更高版本的包中定义。

许多项目仍在更新到这些版本。强烈建议您升级代码生成和工具链以从新功能中受益。


推荐阅读