Friday 24 November 2017

go - Why can I not use func literal as custom func type despite matching parameters in golang?

itemprop="text">


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 href="https://stackoverflow.com/questions/19334542/why-can-i-type-alias-functions-and-use-them-without-casting">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?



Answer




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.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...