为了账号安全,请及时绑定邮箱和手机立即绑定

如何将 Protobuf 的时间戳库与 Go 的时间库一起使用

如何将 Protobuf 的时间戳库与 Go 的时间库一起使用

Go
郎朗坤 2023-03-29 15:14:13
Import fromgithub.com/golang/protobuf/ptypes/timestamp提供了 Protobuf 的本机时间戳实现,可以在您的 protobuf 定义中使用来表示时间。仔细查看timestamp.pb.go所提供的文件,它生成了struct如下内容:type Timestamp struct {    Seconds int64 `protobuf:"varint,1,opt,name=seconds,proto3" json:"seconds,omitempty"`    Nanos                int32    `protobuf:"varint,2,opt,name=nanos,proto3" json:"nanos,omitempty"`    XXX_NoUnkeyedLiteral struct{} `json:"-"`    XXX_unrecognized     []byte   `json:"-"`    XXX_sizecache        int32    `json:"-"`}里面有一些注释示例,timestamp.pb.go但我不是很理解。time 在 go 的库中使用它。我不确定我应该如何设置Timestamp. 我假设这两种类型之间的“转换”并不困难,但我对 Go 和 protobuf 不陌生。任何帮助,将不胜感激。
查看完整描述

1 回答

?
慕的地6264312

TA贡献1817条经验 获得超6个赞

您必须手动将其转换为 time.Time。

对于非指针值:

if !u.Timestamp.IsZero() {
    timestamp, _ := ptypes.TimestampProto(u.Timestamp)
    up.Timestamp = timestamp
}

对于指针值:

if u.Timestamp != nil {
    timestamp, _ := ptypes.TimestampProto(*u.Timestamp)
    up.Timestamp = timestamp
}


查看完整回答
反对 回复 2023-03-29
  • 1 回答
  • 0 关注
  • 165 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信