英文:
Go func with generics and parameters
问题
我是新手,正在学习Golang,之前是使用Node.js开发的。在TypeScript中,可以在函数中使用泛型,并同时传递其他参数,但我想知道在Golang中是否也能实现类似的功能。
例如,在TypeScript中可以这样写:
private async request<T>(query: string, variables: object): Promise<T> {....}
我尝试在Golang中实现类似的功能,但没有成功。我目前的代码如下:
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
}
// 我想在这个函数中使用泛型,以便可以多次重用它
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"})
}
希望能得到帮助,实现这个功能。
英文:
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.
答案1
得分: 2
声明的方式,request
是 *Mwapp
的一个方法。要使它成为一个泛型函数的唯一方法是使 Mwapp
成为泛型。另一种方法是将 request
声明为一个函数而不是一个方法。然后,您可以使它成为泛型而不使 Mwapp
成为泛型类型:
func request[T](mwapp *Mwapp, handler Handler[T]) (*T, error) {
}
英文:
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) {
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论