尽管在 golang 中匹配参数,为什么我不能将 func 文字用作自定义 func 类型?
Why can I not use func literal as custom func type despite matching parameters in golang?
包 google.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...)
}
}
但是我得到这个错误:
"cannot use func literal (type func("context".Context, string, interface {}, interface {}, *grpc.ClientConn, grpc.UnaryInvoker, ...grpc.CallOption) 错误)作为在 return 参数中键入 grpc.UnaryClientInterceptor"
查看 Why can I type alias functions and use them without casting? 我的印象是 return 在我的 clientInterceptor()
中编辑的匿名函数应该匹配 grpc.ClientInterceptor
类型。
此外,来自类型标识规范 (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.
我试过转换和制作 grpc.UnaryClientInterceptor
类型的变量,但没有任何效果。
我也用 grpc.UnaryServerInterceptor
做了基本相同的事情,没有遇到任何问题。
我在这里错过了什么?
您引用的 context
包可能与您的 grpc
版本不同。从 Go 1.7 开始,包从 golang.org/x/net/context
移动到 context
,编译器可能不认为它们是等价的。
包 google.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...)
}
}
但是我得到这个错误:
"cannot use func literal (type func("context".Context, string, interface {}, interface {}, *grpc.ClientConn, grpc.UnaryInvoker, ...grpc.CallOption) 错误)作为在 return 参数中键入 grpc.UnaryClientInterceptor"
查看 Why can I type alias functions and use them without casting? 我的印象是 return 在我的 clientInterceptor()
中编辑的匿名函数应该匹配 grpc.ClientInterceptor
类型。
此外,来自类型标识规范 (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.
我试过转换和制作 grpc.UnaryClientInterceptor
类型的变量,但没有任何效果。
我也用 grpc.UnaryServerInterceptor
做了基本相同的事情,没有遇到任何问题。
我在这里错过了什么?
您引用的 context
包可能与您的 grpc
版本不同。从 Go 1.7 开始,包从 golang.org/x/net/context
移动到 context
,编译器可能不认为它们是等价的。