简体   繁体   中英

Go func with generics and parameters

I am new to Golang and come from nodejs development. in typescript it is possible to use generic in function while passing other parameters as well but I wonder if i can accomplish similar thing with Golang.

For example in typescript one can use

  private async request<T>(query: string, variables: object): Promise<T> {....}

I am trying similar thing in golang with no success. What I have right now is

type Mwapp struct {
    Debug     bool            `json:"debug"`
    Context   context.Context `json:"-"`
    Client    graphql.Client  `json:"-"`
}

type Handler[T any] struct {
    caller        func(ctx context.Context, client graphql.Client) (*T, error)
    operationName string
}

//i WANT TO USE GENERICS IN THIS FUNCTION SO THAT I CAN REUSE IT MULTIPLE TIMES
func (mwapp *Mwapp) request[PASS_HERE_GENERIC](handler Handler[T]) (*T, error) {
    res, err := handler.caller(mwapp.Context, mwapp.Client)

    return res, err
}

func (mwapp *Mwapp) GetMyAccount() (*myAccountResponse, error) {
    return mwapp.request(Handler[myAccountResponse]{myAccount, "GetMyAccount"})
}

func (mwapp *Mwapp) GetMyApp() (*myMwappResponse, error) {
    return mwapp.request(Handler[myMwappResponse]{myApp, "GetMyApp"})
}

Any help to accomplish this will be appreciated.

The way it is declared, request is a method of *Mwapp . The only way to make it a generic function is my making Mwapp generic. Another way of doing this is by declaring request as a function instead of a method. Then you can make it generic without making Mwapp a generic type:

func request[T](mwapp &Mwapp, handler Handler[T]) (*T, error) {
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM