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

dar*_*ing 5 middleware go grpc

google.golang.org/grpc定义类型UnaryClientInterceptor为:

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

在我的代码中,我想做的事情如下:

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...)
    }
}
Run Code Online (Sandbox Code Playgroud)

但是我收到此错误:

"不能使用func文字(类型func("context".Context,string,interface {},interface {},*grpc.ClientConn,grpc.UnaryInvoker,... grpc.CallOption)error)作为返回类型grpc.UnaryClientInterceptor说法"

看看为什么我可以键入别名函数并在不进行转换的情况下使用它们?我得到的印象是,我的返回的匿名函数clientInterceptor()应该与grpc.ClientInterceptor类型匹配.

此外,从类型标识的规范(http://golang.org/ref/spec#Type_identity)

如果两个函数类型具有相同数量的参数和结果值,相应的参数和结果类型相同,并且两个函数都是可变参数或两者都不是,则它们是相同的.参数和结果名称不需要匹配.

我已经尝试过铸造和制作类型的变量,grpc.UnaryClientInterceptor但没有任何作用.

我也基本上做了同样的事情grpc.UnaryServerInterceptor并且没有问题.

我在这里错过了什么?

Adr*_*ian 5

您可能会以context不同于您的版本的方式引用该软件包grpc.从Go 1.7开始,包从golang.org/x/net/contextjust 移到just context,编译器可能看不到它们是等价的.