Need help understanding what this type of function is

I’m having trouble understanding the flow of this function.

  1. Is the ‘internal’ function an anonymous function? Just trying to get the terminology right.

  2. The NewHandler function should return an object of type sdk.Handler, right? But the internal function returns a pointer to an sdk.Result and an error object. I don’t understand what’s happening there, how can *sdk.Result, error be returned as a single (and different Type) sdk.Handler?

  func NewHandler(keeper Keeper) sdk.Handler {
    	return func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) {
    		switch msg := msg.(type) {
    		case MsgSetName:
    			return handleMsgSetName(ctx, keeper, msg)
    			return nil, sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, fmt.Sprintf("Unrecognized nameservice Msg type: %v", msg.Type()))

sdk.Handler is located here for reference:

type Handler func(ctx Context, msg Msg) (*Result, error)

I know that the code itself is definitely right, I just don’t understand how this is working and also not sure what the right terminology is to be able to look things up.

  1. You can also understand it to be closure.
  2. I read func(ctx Context, msg Msg) (*Result, error) as a function that returns (*Result, error). So type Handler func(ctx Context, msg Msg) (*Result, error) is just a type alias for that function. So func NewHandler(keeper Keeper) sdk.Handler {...} is a function called NewHandle that returns a Handler
1 Like

Thanks @laiboonh!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.