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



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

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

在我的代码中,我想做这样的事情:

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...)
}
}

但是我收到此错误:

"不能使用 func 文字(类型 func("context".上下文, 字符串, 接口 {}, 接口 {}, *grpc.ClientConn, grpc.UnaryInvoker, ...GRPC.调用选项)错误)作为 grpc 类型。返回参数中的 UnaryClientInterceptor">

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

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

如果两个函数类型具有相同数量的参数和结果

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

我尝试过转换和制作grpc.UnaryClientInterceptor类型的变量,但没有任何效果。

我也对grpc.UnaryServerInterceptor做了基本上完全相同的事情,没有任何问题。

我在这里错过了什么?

您可能引用context包的方式与grpc版本不同。从Go 1.7开始,包从golang.org/x/net/context移动到context,编译器可能不认为它们是等价的。

最新更新