Go语言中如何检查所有数组长度是否一致?
解决Go中多类型数组长度检查问题
原函数的问题在于:Go语言中[]string、[]int这类具体类型的切片不能直接赋值给[]any类型参数——因为切片类型不具备协变性,[]T和[]any是完全不同的类型,底层存储结构有差异。
想要支持多类型切片的长度检查,最简洁的方案就是使用Go 1.18+引入的泛型,以下是实现代码:
func checkArrayLengthsMatch[T any](desiredLength int, arrays ...[]T) bool { for _, array := range arrays { if len(array) != desiredLength { return false } } return true }
调用示例
func main() { array1 := []string{"1", "2"} array2 := []int{1, 2} // 同类型切片直接批量检查 fmt.Println(checkArrayLengthsMatch(2, array1, array1)) // 输出: true // 混合不同类型切片时,可分别调用后合并结果 res1 := checkArrayLengthsMatch(2, array1) res2 := checkArrayLengthsMatch(2, array2) fmt.Println(res1 && res2) // 输出: true }
如果需要一次性传入不同类型的切片,还可以用另一种泛型写法,适配所有具备长度特性的类型(所有切片天然满足):
type Lenable interface { Len() int } func checkLengthsMatch(desiredLength int, items ...Lenable) bool { for _, item := range items { if item.Len() != desiredLength { return false } } return true } // 调用时将切片转为Lenable接口即可 func main() { array1 := []string{"1", "2"} array2 := []int{1, 2} fmt.Println(checkLengthsMatch(2, Lenable(array1), Lenable(array2))) // 输出: true }
第一种泛型写法更直观,适合同类型切片的批量检查;第二种则支持混合不同类型切片一次性传入,灵活性更高。
内容的提问来源于stack exchange,提问作者elihpoivulp
相关产品推荐
相关产品推荐

