英文:
Check if all array lengths match in Go
问题
我有一个函数,用于检查数组的长度是否相同:
func checkArrayLengthsMatch(desiredLength int, arrays ...[]any) bool {
for _, array := range arrays {
if len(array) != desiredLength {
return false
}
}
return true
}
但是这段代码由于 []any
的存在而无法正常工作。
array1 := []string{"1", "2"}
array2 := []int{1, 2}
checkArrayLengthsMatch(2, array1, array2)
会报错 cannot use array1 (variable of type []string) as type []any in argument to checkArrayLengthsMatch
。
有没有办法在不编写冗长的 if 语句(例如 if len(array1) != 2 || len(array2) != 2
)的情况下实现这个功能?是否可以使用泛型?
我希望能够支持检查各种类型的数组。
Go Playground 链接:https://go.dev/play/p/yKisBIOZktI
英文:
I have a function which checks if array lengths are the same:
func checkArrayLengthsMatch(desiredLength int, arrays ...[]any) bool {
for _, array := range arrays {
if len(array) != desiredLength {
return false
}
}
return true
}
But this doesn't work because of the []any
.
array1 := []string{"1", "2"}
array2 := []int{1, 2}
checkArrayLengthsMatch(2, array1, array2)
gives the error cannot use array1 (variable of type []string) as type []any in argument to checkArrayLengthsMatch
Is there any way to achieve this functionality without having to write a long if statement? (e.g. if len(array1) != 2 || len(array2) != 2
) Generics?
I want to be able to support checking arrays of various types.
Go playground link: https://go.dev/play/p/yKisBIOZktI
答案1
得分: 3
如果您需要将不同类型的数组传递给同一个函数,泛型将无法工作,但反射可以解决:
func checkArrayLengthsMatch(desiredLength int, arrays ...interface{}) bool {
for _, array := range arrays {
if reflect.ValueOf(array).Len() != desiredLength {
return false
}
}
return true
}
这个函数也适用于映射、通道和字符串。
英文:
If you need to pass different types of arrays to the same function, generics won't work, but reflection will:
func checkArrayLengthsMatch(desiredLength int, arrays ...any) bool {
for _, array := range arrays {
if reflect.ValueOf(array).Len() != desiredLength {
return false
}
}
return true
}
This will also work for maps, channels, and strings.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论