You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在.proto文件中正确导入并使用timestamppb包?

解决Protobuf中Timestamp类型导入与使用问题

你犯了一个常见错误:在.proto文件里使用了Go的包路径来导入,这不符合Protobuf的语法规范。Protobuf文件需要导入官方标准的Timestamp定义文件,而非Go模块的路径。

正确的.proto代码应该这样写:

syntax = "proto3";

// 导入官方标准的Timestamp proto定义
import "google/protobuf/timestamp.proto";

message Example {
  // 使用标准的Timestamp类型
  google.protobuf.Timestamp example_time = 1;
}

编译后生成的Go代码会自动使用timestamppb.Timestamp类型,你可以直接用它的AsTime()方法转换成Go的time.Time,也可以用timestamppb.New(time.Now())把time.Time转成timestamppb.Timestamp,完全满足你的转换需求。

编译时无需额外配置,只要你已经正确安装了google.golang.org/protobuf模块,protoc-gen-go插件会自动找到对应的标准proto定义文件。

内容的提问来源于stack exchange,提问作者Nikolaj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 05:31:37