登录
首页 >  Golang >  Go问答

在golang中如何使用泛型来合并两个函数

来源:stackoverflow

时间:2024-03-22 21:12:33 294浏览 收藏

在 Go 语言中,使用泛型可以合并两个函数,使它们能够处理不同类型切片的连接操作。通过使用 `reflect` 包,可以编写一个函数 `concat`,该函数可以连接任意类型的切片。但是,当参数类型不同时,该函数可能会产生混乱。一个更好的解决方案是使用 Go 的类型参数功能,它允许您接受任何类型的参数并将其附加到一个数组中,但需要进行类型断言才能访问特定类型的字段。

问题内容

我有这两个函数,我想在其上实现泛型。只是为了知道我尝试了 interface{}[t any](t any) 和所有字段。这就是代码。如果您知道如何使用泛型将这两个函数合并为一个函数。直接写代码

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
}

directory_account_price_discount_tax 的结构为

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

正确答案


使用 reflect 包编写一个连接任意类型切片的函数。

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()
}

当没有参数或参数类型不同时,函数会发生混乱。

像这样使用 concat 函数:

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

请注意使用 type assertion 来获取所需类型的结果。

使用 go 的 type parameters 功能有一个更好的解决方案,但在我撰写此答案时该功能尚未发布。

这就是您可以接受任何类型的值并将其附加到的方式一个数组。

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

但是当您需要访问 directory_account_price_discount_tax 的字段时,您需要像这样的类型断言

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

今天关于《在golang中如何使用泛型来合并两个函数》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>