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

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 不陌生。任何帮助,将不胜感激。



郎朗坤
浏览 168回答 1
1回答

慕的地6264312

您必须手动将其转换为 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 }
打开App,查看更多内容
随时随地看视频慕课网APP