检查Go中的所有数组长度是否匹配

huangapple go评论79阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2022年10月20日 01:36:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/74129666.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定