如何创建一个方法,什么需要一个泛型切片,其中 X 型结构的切片具有共享泛型字段

How to create a method what takes a generic slice where that slice of type X struct has a shared generic field

提问人:arturfil 提问时间:6/10/2023 更新时间:6/10/2023 访问量:24

问:

我有两个结构体和我的函数,它以 X 类型的切片作为参数,返回给定切片的总量

type Food struct {
    name string
    price float64
}

type Cloth {
    name string
    price int
}

func AddItemsAlt[T Cloth | Food](objects []T, getUnit func(obj T) float64) float64 {
    sum := 0.0
    for _, obj := range objects {
        sum += getUnit(obj)
    }
    return sum
}

func main() {
    var check = []Food {{"Pizza", 6.23}, {"Hamburgesa", 7.99}, {"Tacos", 4.34}}
    var cart = []Cloth {{"Player", 6}, {"Pants", 8}, {"Tacos de Futbol", 10}}


    check := AddItems(cart, func(obj Food) float64 {
        return obj.price
    })
}

我会尝试这个,它会给我一个错误,因为该函数没有考虑到 Cloth 可能将字段作为 int 类型这一事实。

函数 go 泛型嵌 套切

评论


答:

0赞 arturfil 6/10/2023 #1

我继续更新我的答案,添加两个接口并将这些接口放入功能中

type Food struct {
    name string
    price float64
}

type Cloth {
    name string
    price int
}

type Amount interface {
    int | float64
}

type Item interface {
    Cloth | Food
}

func AddItemsAlt[T Item, A Amount](objects []T, getUnit func(obj T) A) A {
    sum := A(0)
    for _, obj := range objects {
        sum += getUnit(obj)
    }
    return sum
}

func main() {
    var check = []Food {{"Pizza", 6.23}, {"Hamburgesa", 7.99}, {"Tacos", 4.34}}
    var cart = []Cloth {{"Player", 6}, {"Pants", 8}, {"Tacos de Futbol", 10}}


    check := AddItems(check, func(obj Food) float64 {
        return obj.price
    })
    cartTotal := AddItems(cart, func(obj Cloth) int {
        return obj.price
    })

    fmt.Printf("The total for the shopping cart is:\t%v\n", cartTotal)
    fmt.Printf("The total for the check is:\t%.4f\n", check)

}