亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

具有可變輸入/輸出類型的通用函數

具有可變輸入/輸出類型的通用函數

Go
江戶川亂折騰 2023-06-19 14:01:46
只是玩 aws sdk for go。當列出不同類型的資源時,我傾向于使用很多非常相似的函數,例如下面示例中的兩個。有沒有辦法將它們重寫為一個通用函數,該函數將根據作為參數傳遞的內容返回特定類型?就像是:func generic(session, funcToCall, t, input) (interface{}, error) {}目前我必須這樣做(功能是相同的,只是類型發生了變化):func getVolumes(s *session.Session) ([]*ec2.Volume, error) {    client := ec2.New(s)    t := []*ec2.Volume{}    input := ec2.DescribeVolumesInput{}    for {        result, err := client.DescribeVolumes(&input)        if err != nil {            return nil, err        }        t = append(t, result.Volumes...)        if result.NextToken != nil {            input.NextToken = result.NextToken        } else {            break        }    }    return t, nil}func getVpcs(s *session.Session) ([]*ec2.Vpc, error) {    client := ec2.New(s)    t := []*ec2.Vpc{}    input := ec2.DescribeVpcsInput{}    for {        result, err := client.DescribeVpcs(&input)        if err != nil {            return nil, err        }        t = append(t, result.Vpcs...)        if result.NextToken != nil {            input.NextToken = result.NextToken        } else {            break        }    }    return t, nil} 
查看完整描述

2 回答

?
慕哥9229398

TA貢獻1877條經驗 獲得超6個贊

因為您只處理函數,所以可以使用 reflect 包在運行時生成函數。

使用對象類型 (Volume, Vpc) 可以導出所有后續信息,以提供一個完全通用的實現,該實現非??菰?,甚至更復雜、更慢。


package main


import (

? ? "errors"

? ? "fmt"

? ? "reflect"

)


func main() {

? ? fmt.Printf("%T\n", getter(Volume{}))

? ? fmt.Printf("%T\n", getter(Vpc{}))

}


type DescribeVolumesInput struct{}

type DescribeVpcs struct{}


type Volume struct{}

type Vpc struct{}


type Session struct{}


type Client struct{}


func New(s *Session) Client { return Client{} }


var typeRegistry = make(map[string]reflect.Type)


func init() {

? ? some := []interface{}{DescribeVolumesInput{}, DescribeVpcs{}}

? ? for _, v := range some {

? ? ? ? typeRegistry[fmt.Sprintf("%T", v)] = reflect.TypeOf(v)

? ? }

}


var errV = errors.New("")

var errType = reflect.ValueOf(&errV).Elem().Type()

var zeroErr = reflect.Zero(reflect.TypeOf((*error)(nil)).Elem())

var nilErr = []reflect.Value{zeroErr}


func getter(of interface{}) interface{} {


? ? outType := reflect.SliceOf(reflect.PtrTo(reflect.TypeOf(of)))

? ? fnType := reflect.FuncOf([]reflect.Type{reflect.TypeOf(new(Session))}, []reflect.Type{outType, errType}, false)

? ? fnBody := func(input []reflect.Value) []reflect.Value {


? ? ? ? client := reflect.ValueOf(New).Call(input)[0]


? ? ? ? t := reflect.MakeSlice(outType, 0, 0)

? ? ? ? name := fmt.Sprintf("Describe%TsInput", of)

? ? ? ? descInput := reflect.New(typeRegistry[name]).Elem()


? ? ? ? mName := fmt.Sprintf("Describe%Ts", of)

? ? ? ? meth := client.MethodByName(mName)

? ? ? ? if !meth.IsValid() {

? ? ? ? ? ? return []reflect.Value{

? ? ? ? ? ? ? ? t,

? ? ? ? ? ? ? ? reflect.ValueOf(fmt.Errorf("no such method %q", mName)),

? ? ? ? ? ? }

? ? ? ? }

? ? ? ? for {

? ? ? ? ? ? out := meth.Call([]reflect.Value{descInput.Addr()})

? ? ? ? ? ? if len(out) > 0 {

? ? ? ? ? ? ? ? errOut := out[len(out)-1]

? ? ? ? ? ? ? ? if errOut.Type().Implements(errType) && errOut.IsNil() == false {

? ? ? ? ? ? ? ? ? ? return []reflect.Value{t, errOut}

? ? ? ? ? ? ? ? }

? ? ? ? ? ? }

? ? ? ? ? ? result := out[1]

? ? ? ? ? ? fName := fmt.Sprintf("%Ts", of)

? ? ? ? ? ? if x := result.FieldByName(fName); x.IsValid() {

? ? ? ? ? ? ? ? t = reflect.AppendSlice(t, x)

? ? ? ? ? ? } else {

? ? ? ? ? ? ? ? return []reflect.Value{

? ? ? ? ? ? ? ? ? ? t,

? ? ? ? ? ? ? ? ? ? reflect.ValueOf(fmt.Errorf("field not found %q", fName)),

? ? ? ? ? ? ? ? }

? ? ? ? ? ? }


? ? ? ? ? ? if x := result.FieldByName("NextToken"); x.IsValid() {

? ? ? ? ? ? ? ? descInput.FieldByName("NextToken").Set(x)

? ? ? ? ? ? } else {

? ? ? ? ? ? ? ? break

? ? ? ? ? ? }

? ? ? ? }

? ? ? ? return []reflect.Value{t, zeroErr}

? ? }

? ? fn := reflect.MakeFunc(fnType, fnBody)

? ? return fn.Interface()

}


查看完整回答
反對 回復 2023-06-19
?
月關寶盒

TA貢獻1772條經驗 獲得超5個贊

代理第 3 方 API,用 go 實現非常簡單,下面是它是如何用 endly e2e test runner?AWS 代理實現的

我會說 AWS API 是代理的完美候選者,只要反射性能價格不是問題。

像kubernetes這樣的其他一些第三方 API?更具挑戰性,但仍然很容易用 go 代理,這是反射和代碼生成的結合。


查看完整回答
反對 回復 2023-06-19
  • 2 回答
  • 0 關注
  • 159 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號