代码之家  ›  专栏  ›  技术社区  ›  Mario Stoilov

Go protobuf无法识别相同的包

  •  1
  • Mario Stoilov  · 技术社区  · 8 年前

    我有一些使用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{})
        ...
    }
    

    我得到以下错误:

    无法使用“*google\u protobuf”。空{}(类型 “myproject/vendor/github.com/golang/protobuf/ptypes/empty”。空)as 类型 “myproject/vendor/github.com/golang/protobuf/ptypes/empty”*google\u协议。空的

    它们是相同的东西(它们甚至解析为相同的文件)。我错过了什么?

    1 回复  |  直到 8 年前
        1
  •  2
  •   Marc    8 年前

    您的错误在这一行:

     _, 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