簡體   English   中英

如何使用 *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]

我相信我的分配不正確,但是為什么以及如何解決這個問題以正確分配而不會使我的系統崩潰?

Go 的time.Time是一個具有非公共字段的結構,不能直接通過協議緩沖區發送。

而是將任何time.Time值轉換為 google 的 protobuf 時間類型。 (在幕后,這是一個簡單的unixtime ,即自 1970 年以來的秒數加上沒有時區信息的納秒 - 請參見此處

例如,在您的.proto文件中:

syntax = "proto3";

import "google/protobuf/timestamp.proto";

message MyData {
    google.protobuf.Timestamp   updated             = 1;
    google.protobuf.Timestamp   created             = 2;
}

在您的 go 代碼中:

import (
    "time"

    "github.com/golang/protobuf/ptypes"
)

// ...

updatedTime := time.Now()
updatedProto, err := ptypes.TimestampProto(updatedTime)

// ...

mydate := &pb.MyData{
    updated: updatedProto,
}

正如你所擁有的

*res.CurentTime = time.Now()

將首先取消引用res.CurentTime (這就是*在這里所做的),如果它是nil ,將立即恐慌。 之后發生的事情並不重要。 相反,您需要分配一個指針,而不是為現有( nil )指針分配一個新值:

now := time.Now()
res.CurentTime = &now

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM