按标题提问。
尝试以 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: ×tamp.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.go
与 protoc --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/