当前位置: > > > > 使用泛型和参数进行 Go func
来源:stackoverflow
2024-04-26 08:45:38
0浏览
收藏
学习Golang要努力,但是不要急!今天的这篇文章《使用泛型和参数进行 Go func》将会介绍到等等知识点,如果你想深入学习Golang,可以关注我!我会持续更新相关文章的,希望对大家都能有所帮助!
问题内容
我是 golang 新手,来自 nodejs 开发。在打字稿中,可以在函数中使用泛型,同时传递其他参数,但我想知道我是否可以使用 golang 完成类似的事情。
例如,在打字稿中可以使用
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 } //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"}) }
任何帮助实现这一目标的帮助都将不胜感激。
正确答案
从声明方式来看,request
是 *mwapp
的方法。使其成为通用函数的唯一方法是使 mwapp
通用。另一种方法是将 request
声明为函数而不是方法。然后,您可以使其通用,而无需将 mwapp
设为泛型类型:
func request[T](mwapp &Mwapp, handler Handler[T]) (*T, error) { }
今天关于《使用泛型和参数进行 Go func》的内容介绍就到此结束,如果有什么疑问或者建议,可以在公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!