Home > database >  how to use generics to merge two function in one in golang
how to use generics to merge two function in one in golang

Time:11-01

i have this two functions and i want to implement generics on it. just to know i tried interface{} and [t any] and (t any) and all field. and this is the code. if you know how to use generics to make this two functions in one function. just write the code

func concat(args ...[]directory_account_price_discount_tax) []directory_account_price_discount_tax {
    concated := []directory_account_price_discount_tax{}
    for _, i := range args {
        concated = append(concated, i...)
    }
    return concated
}

func concat_strings_slice(args ...[]string) []string {
    concated := []string{}
    for _, i := range args {
        concated = append(concated, i...)
    }
    return concated
}

and the struct of directory_account_price_discount_tax is

type directory_account_price_discount_tax struct {
    directory_no         []int
    Account              string
    Price, Discount, Tax float64
}

CodePudding user response:

This is how you can accept any kind of value and append them to an array.

func concat(args ...interface{}) []interface{} {
    concated := make([]interface{}, 0)
    for _, i := range args {
        concated = append(concated, i)
    }
    return concated
}

But when you need to access the fields of directory_account_price_discount_tax you need type assertion like this

arr := concat(/* some directory_account_price_discount_tax type values */)
v := arr[0].(directory_account_price_discount_tax)

CodePudding user response:

Use the reflect package to write a function that concatenates slices of an arbitrary type.

func concat(args ...interface{}) interface{} {
    n := 0
    for _, arg := range args {
        n  = reflect.ValueOf(arg).Len()
    }
    v := reflect.MakeSlice(reflect.TypeOf(args[0]), 0, n)
    for _, arg := range args {
        v = reflect.AppendSlice(v, reflect.ValueOf(arg))
    }
    return v.Interface()
}

The function panics when there are no arguments or the arguments are not the same type.

Use the concat function like this:

s := concat([]string{"a", "b"}, []string{"c", "d"}).([]string)

Note the use of the type assertion to get result as the desired type.

There is a better solution using Go's type parameters feature, but that feature is not released as of the time I am writing this answer.

  •  Tags:  
  • go
  • Related