gpt4 book ai didi

go - 处理不同数据类型的方法

转载 作者:数据小太阳 更新时间:2023-10-29 03:42:48 26 4
gpt4 key购买 nike

我想制作一个接受不同数据类型的方法,但 Go 没有泛型。我必须编写以下重复代码:

func GetRandomSubarrayInt64(candidates []int64, length int) []int64 {
result := make([]int64, 0, length)
if len(candidates) == 0 {
return result
}
if len(candidates) <= length {
return candidates
}
rand.Shuffle(len(candidates), func(i, j int) {
candidates[i], candidates[j] = candidates[j], candidates[i]
})
return candidates[:length]
}


func GetRandomSubarrayString(candidates []string, length int) []string {
result := make([]string, 0, length)
if len(candidates) == 0 {
return result
}
if len(candidates) <= length {
return candidates
}
rand.Shuffle(len(candidates), func(i, j int) {
candidates[i], candidates[j] = candidates[j], candidates[i]
})
return candidates[:length]
}

代码几乎是重复的,有没有办法减少重复代码?

最佳答案

您可以定义一个接口(interface),该接口(interface)导出方法以交换通用底层数组中的项目。然后,您将需要使用特定于类型的数组/slice 来实现此接口(interface)。类似于 this .

type ShuffleSlice interface {
Swap(i, j int)
Len() int
}

func GetRandomSubslice(candidates ShuffleSlice) ShuffleSlice {
if candidates == nil || candidates.Len() == 0 {
return nil
}
rand.Shuffle(candidates.Len(), func(i, j int) {
candidates.Swap(i, j)
})
return candidates
}

type ShuffleSliceInt []int

func (s ShuffleSliceInt) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}

func (s ShuffleSliceInt) Len() int {
return len(s)
}

关于go - 处理不同数据类型的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56895727/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com