go protobuf : Cannot find package "." in github. com/gogo/protobuf/proto 和 m.TimeStamp.MarshalToSizedBuffer 未定义

标签 go protocol-buffers protoc

按标题提问。
尝试以 2 种方式编译 gogoproto 和 golangprotobuf。

为两者编写测试,两者都不会编码。

msg.proto

syntax = "proto3";

import "google/protobuf/timestamp.proto";

package msg;

message Message {
    string Name = 1;
    google.protobuf.Timestamp TimeStamp = 2;
}


demo_test.go
package msg

import (
    "testing"
    "time"

    // gogo "github.com/gogo/protobuf/proto"
    "github.com/golang/protobuf/proto"
    "github.com/golang/protobuf/ptypes/timestamp"
)

var msg = Message{
    Name:      "demo",
    TimeStamp: &timestamp.Timestamp{Seconds: int64(time.Now().Second())},
}

//func TestGogoMessage_Marshal(t *testing.T) {
//  myBytes, err := gogo.Marshal(&msg)
//  if err != nil {
//      t.Fail()
//  }

//  _ = myBytes
//}

func TestProtoMessage_Marshal(t *testing.T) {
    myBytes, err := proto.Marshal(&msg)
    if err != nil {
        t.Fail()
    }

    _ = myBytes
}

编译:
protoc --gofast_out=. ./demo/msg.proto有效,但运行测试:
# github.com/.../demo
package github.com/.../demo (test)
    imports github.com/gogo/protobuf/proto: cannot find package "." in:
    /Users/.../vendor/github.com/gogo/protobuf/proto
protoc --go_out=. ./demo/msg.proto有效,但运行测试:
# github.com/.../demo [github.com/.../demo.test]
./msg.pb.go:127:28: m.TimeStamp.MarshalToSizedBuffer undefined (type *timestamp.Timestamp has no field or method MarshalToSizedBuffer)
./msg.pb.go:169:18: m.TimeStamp.Size undefined (type *timestamp.Timestamp has no field or method Size)
./msg.pb.go:277:25: m.TimeStamp.Unmarshal undefined (type *timestamp.Timestamp has no field or method Unmarshal)

最佳答案

这两个命令对我来说都很好,所以,问题可能出在你的环境中。

关于undefine错误,您使用的似乎是 Timestamp结构来自 github.com/golang/protobuf/ptypes/timestamp ,其接口(interface)与 Timestamp 不同来自 https://github.com/gogo/protobuf/blob/master/types/timestamp.pb.go .所以如果你生成msg.pb.goprotoc --gofast_out=. ./demo/msg.proto您将收到此错误。

关于go protobuf : Cannot find package "." in github. com/gogo/protobuf/proto 和 m.TimeStamp.MarshalToSizedBuffer 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61170043/

相关文章:

go - 如何使用Golang解析ndjson文件? [复制]

go - 模板.执行(): invalid memory address or nil pointer dereference

protocol-buffers - 与 Protobuf 一起使用的日期和时间类型

java - 使用 Maven 插件生成 Protocol Buffer 会导致版本错误

go - 如何将任何类型的数据值传递到 Golang 中的 GRPC Protobuf 结构中?

go - 将 json.RawMessage 解码到反射 slice

arrays - 无效操作 : index of type *int golang

protocol-buffers - Protobuf 找不到共享库

java - eclipse中hadoop中的protoc错误

python-3.x - 使用 Python 的 Protocol Buffer 选择使用 SerializeToString 的数据顺序