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 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算