【发布时间】:2021-06-02 11:04:24
【问题描述】:
我想写一个函数,它接受一个“特殊”数组并在 Golang 中返回其乘积和。(嵌套越多,乘数增加 1)
这是使用接口的解决方案之一,但我不确定为什么此代码有效。我理解一般逻辑,但不确定为什么“接口”可以区分当前元素是否是一种“特殊”数组。 (包含切片)。
由于我们传递了一个类型为 SpecialArray 接口的数组,所有范围内的元素都可能是 SpecialArray 类型,所以看起来没有机会进入 else 语句。 Golang 中是否有类似内置“SpecialArray”接口的东西?
这里是输入值和输出的例子。array = [5, 2, [7, -1], 3, [6, [-13, 8], 4]] => output = 12 // 5 + 2 + 2 *( 7 -1) +3 + 2 * (6 + 3 * (-13 +8) + 4)
package main
type SpecialArray []interface{}
func ProductSum(array []interface{}) int {
return helper(array, 1)
}
func helper(array SpecialArray, multiplier int) int {
sum := 0
// loop passed array
for _, element := range array {
if cast, ok := element.(SpecialArray); ok {
sum += helper(cast, multiplier + 1)
} else if cast, ok := element.(int); ok {
sum += cast
}
}
return sum * multiplier
}
【问题讨论】: