如何在Go的时间库中使用Protobuf的时间戳库

问题描述 投票:1回答:1

github.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里面有一些评论的例子,但我不太了解它。

与go的time library一起使用它。我不确定我是怎么设置Timestamp里面的字段的。我假设两种类型之间的“转换”并不困难,但我不再使用Go和protobuf。任何帮助,将不胜感激。

go protocol-buffers
1个回答
1
投票

您必须手动将其转换为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
}
© www.soinside.com 2019 - 2024. All rights reserved.