gpt4 book ai didi

go - 如何使用 *time.Time 在 Protocol Buffer 的结构中声明

转载 作者:行者123 更新时间:2023-12-01 22:37:59 25 4
gpt4 key购买 nike

我在 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]

我相信我做的分配不正确,但是为什么以及如何解决这个问题以正确分配而不会使我的系统崩溃?

最佳答案

围棋time.Time是一个结构体 non-public fields不能直接通过 Protocol Buffer 发送。

而是转换任何 time.Time谷歌的 protobuf 时间类型的值。
(在幕后,这是一个简单的 unixtime,即自 1970 年以来的秒数加上没有时区信息的纳秒 - 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,
}

关于go - 如何使用 *time.Time 在 Protocol Buffer 的结构中声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58826458/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com