如何使用在协议缓冲区结构中声明的 *time.Time
How to use *time.Time declared in struct of protocol buffer
我在协议缓冲区的结构中定义了以下内容:
CurentTime *time.Time `protobuf:"bytes,5,opt,name=curent_time,json=curentTime,proto3,stdtime" json:"curent_time,omitempty"
在我的 main.go 代码中,我尝试按如下方式分配它:
*res.CurentTime = time.Now()
我不断收到以下错误:
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x1642e61]
我认为我的赋值不正确,但是为什么以及如何解决这个问题以正确赋值而不会使我的系统崩溃?
如你所愿
*res.CurentTime = time.Now()
将首先取消引用 res.CurentTime
(这就是 *
在这里所做的),如果它是 nil
,将立即出现恐慌。之后的事情并不重要。相反,您需要分配一个指针,而不是为现有 (nil
) 指针分配一个新值:
now := time.Now()
res.CurentTime = &now
Go 的 time.Time
是一个具有 non-public fields 的结构,不能通过协议缓冲区直接发送。
而是将任何 time.Time
值转换为 google 的 protobuf 时间类型。
(在幕后,这是一个简单的 unixtime,即自 1970 年以来的秒数加上具有 NO 时区信息的纳秒 - see here)
例如,在您的 .proto
文件中:
syntax = "proto3";
import "google/protobuf/timestamp.proto";
message MyData {
google.protobuf.Timestamp updated = 1;
google.protobuf.Timestamp created = 2;
}
在你的代码中:
import (
"time"
"github.com/golang/protobuf/ptypes"
)
// ...
updatedTime := time.Now()
updatedProto, err := ptypes.TimestampProto(updatedTime)
// ...
mydate := &pb.MyData{
updated: updatedProto,
}
我在协议缓冲区的结构中定义了以下内容:
CurentTime *time.Time `protobuf:"bytes,5,opt,name=curent_time,json=curentTime,proto3,stdtime" json:"curent_time,omitempty"
在我的 main.go 代码中,我尝试按如下方式分配它:
*res.CurentTime = time.Now()
我不断收到以下错误:
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x1642e61]
我认为我的赋值不正确,但是为什么以及如何解决这个问题以正确赋值而不会使我的系统崩溃?
如你所愿
*res.CurentTime = time.Now()
将首先取消引用 res.CurentTime
(这就是 *
在这里所做的),如果它是 nil
,将立即出现恐慌。之后的事情并不重要。相反,您需要分配一个指针,而不是为现有 (nil
) 指针分配一个新值:
now := time.Now()
res.CurentTime = &now
Go 的 time.Time
是一个具有 non-public fields 的结构,不能通过协议缓冲区直接发送。
而是将任何 time.Time
值转换为 google 的 protobuf 时间类型。
(在幕后,这是一个简单的 unixtime,即自 1970 年以来的秒数加上具有 NO 时区信息的纳秒 - see here)
例如,在您的 .proto
文件中:
syntax = "proto3";
import "google/protobuf/timestamp.proto";
message MyData {
google.protobuf.Timestamp updated = 1;
google.protobuf.Timestamp created = 2;
}
在你的代码中:
import (
"time"
"github.com/golang/protobuf/ptypes"
)
// ...
updatedTime := time.Now()
updatedProto, err := ptypes.TimestampProto(updatedTime)
// ...
mydate := &pb.MyData{
updated: updatedProto,
}