Casting interface可以反映数组类型。

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

Casting interface can reflecting on array types

问题

下面的代码是对Python脚本的改编。当然,它不能编译,有几个原因。

我很难理解如何修复它以便得到正确的结果。

具体来说:

  1. 我想表示一个类型(float64)或者这个类型的数组,所以我天真地使用了[]interface{},但是传递一个数组是行不通的。我知道我可以使用我的数组来深拷贝一个接口数组,但这是唯一的方法吗?

  2. 反射检查是有效的(有点),但是我又回到了将接口转换为[]interface{},这是行不通的。

  3. 一个更简单的方法是传递[]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:

  1. I want to represent either a type (float64) or an array 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?

  2. The reflection check works (kinda) but then I am back to casting an interface to an []interface and that doesn't work.

  3. A simpler way would be to pass []float but I also want to make the code generic (oops! Casting interface可以反映数组类型。 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)
}

playground 示例

英文:

Here's one way to implement assertArrayEquals:

func assertArrayEquals(first interface{}, second interface{}) bool {
    return reflect.DeepEqual(first, second)
}

playground example

huangapple
  • 本文由 发表于 2016年4月15日 11:05:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/36637566.html
匿名

发表评论

匿名网友

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

确定