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.
CodePudding user response:
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) {
}