英文:
Casting interface can reflecting on array types
问题
下面的代码是对Python脚本的改编。当然,它不能编译,有几个原因。
我很难理解如何修复它以便得到正确的结果。
具体来说:
-
我想表示一个类型(
float64
)或者这个类型的数组,所以我天真地使用了[]interface{}
,但是传递一个数组是行不通的。我知道我可以使用我的数组来深拷贝一个接口数组,但这是唯一的方法吗? -
反射检查是有效的(有点),但是我又回到了将接口转换为
[]interface{}
,这是行不通的。 -
一个更简单的方法是传递
[]float
,但我还想使代码足够通用(糟糕!;-),以接受[][]floats
并递归地进行比较。
我完全偏离了轨道吗?
func assertArrayEquals(first []interface{}, second []interface{}) bool {
if len(first) != len(second) {
return false
}
for i := range first {
if reflect.ValueOf(first[i]).Kind() == reflect.Array {
assertArrayEquals([]interface{}(first[i]), []interface{}(second[i]))
} else if second[i] != first[i] {
return false
}
}
return true
}
func main() {
assertArrayEquals([]float64{[]float64{0, 1}, []float64{0, 1}}, []float64{[]float64{0, 1}, []float64{0, 1}})
}
英文:
The code below is an adaption of a Python script. Of course, it doesn't compile and there are a couple of reasons for this.
I am struggling to understand how it's possible to fix it so it gives the right result.
In particular:
-
I want to represent either a type (
float64
) or anarray
of this type so I am naively using an[]interface
but then passing an array won't work. I understand I could deep copy an interface array with my array but is it the only way? -
The reflection check works (kinda) but then I am back to casting an interface to an
[]interface
and that doesn't work. -
A simpler way would be to pass
[]float
but I also want to make the code generic (oops! enough to accept[][]floats
and recursively descend with the comparisons.
Am I completely offtrack?
func assertArrayEquals(first []interface{}, second []interface{}) bool {
if len(first) != len(second) {
return false
}
for i := range first {
if reflect.ValueOf(first[i]).Kind() == reflect.Array {
assertArrayEquals([]interface{}(first[i]), []interface{}(second[i]))
} else if second[i] != first[i] {
return false
}
}
return true
}
func main() {
assertArrayEquals([]float64{[]float64{0, 1}, []float64{0, 1}}, []float64{[]float64{0, 1}, []float64{0, 1}})
}
答案1
得分: 1
这是一种实现 assertArrayEquals 的方法:
func assertArrayEquals(first interface{}, second interface{}) bool {
return reflect.DeepEqual(first, second)
}
英文:
Here's one way to implement assertArrayEquals:
func assertArrayEquals(first interface{}, second interface{}) bool {
return reflect.DeepEqual(first, second)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论