我正在尝试将protobuf * Timestamp.timestamp写入二进制文件,我得到的错误是invalid type *Timestamp.timestamp
,我试图无济于事,有人能指点我某个方向吗?谢谢!
package main
import (
"bytes"
"encoding/binary"
"fmt"
google_protobuf "github.com/golang/protobuf/ptypes/timestamp"
"time"
)
func main() {
buff := new(bytes.Buffer)
ts := &google_protobuf.Timestamp{
Seconds: time.Now().Unix(),
Nanos: 0,
}
err := binary.Write(buff, binary.LittleEndian, ts)
if err != nil {
panic(err)
}
fmt.Println("done")
}
任何人都能指出我的方向吗?
阅读错误消息。
binary.Write: invalid type *timestamp.Timestamp
阅读binary.Write
和timestamp.Timestamp
的文档。
import "encoding/binary"
func Write(w io.Writer, order ByteOrder, data interface{}) error
Write将数据的二进制表示写入w。数据必须是固定大小的值或固定大小值的片段,或指向此类数据的指针。布尔值编码为一个字节:1表示true,0表示false。写入w的字节使用指定的字节顺序进行编码,并从数据的连续字段中读取。编写结构时,为具有空白(_)字段名称的字段写入零值。
import "github.com/golang/protobuf/ptypes/timestamp"
type Timestamp struct { // Represents seconds of UTC time since Unix epoch // 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to // 9999-12-31T23:59:59Z inclusive. Seconds int64 `protobuf:"varint,1,opt,name=seconds,proto3" json:"seconds,omitempty"` // Non-negative fractions of a second at nanosecond resolution. Negative // second values with fractions must still have non-negative nanos values // that count forward in time. Must be from 0 to 999,999,999 // inclusive. Nanos int32 `protobuf:"varint,2,opt,name=nanos,proto3" json:"nanos,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` }
时间戳表示独立于任何时区或日历的时间点,表示为UTC时间段内纳秒分辨率的秒和分数秒。它使用Proleptic Gregorian Calendar进行编码,将公历向后延伸至第一年。它被编码,假设所有分钟都是60秒长,即闰秒被“模糊”,因此解释时不需要闰秒表。范围是从0001-01-01T00:00:00Z到9999-12-31T23:59:59.999999999Z。通过限制到该范围,我们确保可以转换为RFC 3339日期字符串和从RFC 3339日期字符串转换。见https://www.ietf.org/rfc/rfc3339.txt。
正如错误消息所示:*timestamp.Timestamp
不是固定大小的值或固定大小值的片段,或指向此类数据的指针。
为了确认这一点,请注释掉XXX_unrecognized
可变大小的字段;没有错误。
package main
import (
"bytes"
"encoding/binary"
"fmt"
"time"
)
// https://github.com/golang/protobuf/blob/master/ptypes/timestamp/timestamp.pb.go
type Timestamp struct {
// Represents seconds of UTC time since Unix epoch
// 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
// 9999-12-31T23:59:59Z inclusive.
Seconds int64 `protobuf:"varint,1,opt,name=seconds,proto3" json:"seconds,omitempty"`
// Non-negative fractions of a second at nanosecond resolution. Negative
// second values with fractions must still have non-negative nanos values
// that count forward in time. Must be from 0 to 999,999,999
// inclusive.
Nanos int32 `protobuf:"varint,2,opt,name=nanos,proto3" json:"nanos,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
// XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func main() {
buff := new(bytes.Buffer)
ts := &Timestamp{
Seconds: time.Now().Unix(),
Nanos: 0,
}
err := binary.Write(buff, binary.LittleEndian, ts)
if err != nil {
panic(err)
}
fmt.Println("done")
}
游乐场:https://play.golang.org/p/Q5NGnO49Dsc
输出:
done