简体   繁体   English

Go 函数与 generics 和参数

[英]Go func with generics and parameters

I am new to Golang and come from nodejs development.我是 Golang 的新手,来自 nodejs 开发。 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.在 typescript 中,可以在 function 中使用泛型,同时传递其他参数,但我想知道我是否可以用 Golang 完成类似的事情。

For example in typescript one can use例如在 typescript 一个可以使用

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

I am trying similar thing in golang with no success.我正在 golang 中尝试类似的事情,但没有成功。 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 .它的声明方式, request*Mwapp的一种方法。 The only way to make it a generic function is my making Mwapp generic.使其成为通用 function 的唯一方法是我将Mwapp通用。 Another way of doing this is by declaring request as a function instead of a method.另一种方法是将request声明为 function 而不是方法。 Then you can make it generic without making Mwapp a generic type:然后,您可以使其通用而不使Mwapp成为通用类型:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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