按标题提问。我试着用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/protoprotoc --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)发布于 2020-04-12 19:53:43
这两个命令对我来说都工作得很好,所以,问题可能出在您的环境中。
关于undefine错误,看起来您使用的是来自github.com/golang/protobuf/ptypes/timestamp的Timestamp结构,它具有与https://github.com/gogo/protobuf/blob/master/types/timestamp.pb.go的Timestamp不同的接口。所以如果你用protoc --gofast_out=. ./demo/msg.proto生成msg.pb.go,你会得到这个错误。
https://stackoverflow.com/questions/61170043
复制相似问题