Go protobuf无法识别相同的包

Go protobuf not recognizing identical packages

我有一些使用 google protobuf 的代码。这些是源文件:

原型文件:

syntax = "proto3";

package my_package.protocol;
option go_package = "protocol";

import "github.com/golang/protobuf/ptypes/empty/empty.proto";

...

service MyService {
    rpc Flush        (google.protobuf.Empty) returns (google.protobuf.Empty);
}

编译的go文件:

package protocol

import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
import google_protobuf "github.com/golang/protobuf/ptypes/empty"

import (
    context "golang.org/x/net/context"
    grpc "google.golang.org/grpc"
)

...

type MyServiceClient interface {
    Flush(ctx context.Context, in *google_protobuf.Empty, opts ...grpc.CallOption) (*google_protobuf.Empty, error)
}

当我最终尝试像这样使用编译服务时:

import (
    "golang.org/x/net/context"

    pb "myproject/protocol"

    google_protobuf "github.com/golang/protobuf/ptypes/empty"
)
...
func Flush(sink pb.MyServiceClient) {
    _, err = sink.Flush(context.Background(), *google_protobuf.Empty{})
    ...
}

我收到以下错误:

Cannot use '*google_protobuf.Empty{}' (type "myproject/vendor/github.com/golang/protobuf/ptypes/empty".Empty) as type "myproject/vendor/github.com/golang/protobuf/ptypes/empty".*google_protobuf.Empty

它们是同一回事(它们甚至解析为同一个文件)。我在这里错过了什么?

你的错误在这一行:

 _, err = sink.Flush(context.Background(), *google_protobuf.Empty{})

*google_protobuf.Empty{} 试图取消引用该结构,但您的函数原型需要一个指向 google_protobuf.Empty 的指针。请改用 &google_protobuf.Empty{}。当你最终得到一个真正的数据结构而不是空的时,你可能会按照以下方式做一些事情:

  req := google_protobuf.MyRequestStruct{}
  _, err = service.Method(context.Background(), &req)

Go 中的指针语法概述,请参考 tour