dousou2897 2017-05-10 19:30
浏览 442
已采纳

尽管golang中的参数匹配,为什么我不能将func文字用作自定义func类型?

Package google.golang.org/grpc defines type UnaryClientInterceptor as:

type UnaryClientInterceptor func(ctx context.Context, method string, req, reply interface{}, cc *ClientConn, invoker UnaryInvoker, opts ...CallOption) error

In my code I'd like to do something like:

func clientInterceptor() grpc.UnaryClientInterceptor {
    return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
        //intercept stuff
        return invoker(ctx, method, req, reply, cc, opts...)
    }
}

However I get this error:

"cannot use func literal (type func("context".Context, string, interface {}, interface {}, *grpc.ClientConn, grpc.UnaryInvoker, ...grpc.CallOption) error) as type grpc.UnaryClientInterceptor in return argument"

Looking at Why can I type alias functions and use them without casting? I get the impression that the anonymous function returned in my clientInterceptor() should match the grpc.ClientInterceptor type.

Also, from the spec on Type Identity (http://golang.org/ref/spec#Type_identity)

Two function types are identical if they have the same number of parameters and result values, corresponding parameter and result types are identical, and either both functions are variadic or neither is. Parameter and result names are not required to match.

I've tried casting and making variables of type grpc.UnaryClientInterceptor but nothing works.

I also did essentially the exact same thing with the grpc.UnaryServerInterceptor and had no problems.

What am I missing here?

  • 写回答

1条回答 默认 最新

  • dqa35710 2017-05-10 20:46
    关注

    You may be referencing the context package differently than your version of grpc. As of Go 1.7, the package moved from golang.org/x/net/context to just context, and the compiler likely doesn't see them as equivalent.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line