go语⾔array_sum求和⽅法(反射+泛型)给定⼀个任意类型的切⽚/数组,求所有元素的值
原型:ArraySum(input interface{}) (sum float64, err error)
功能:对 input 切⽚中的所有数据求和,结果累计在 sum 中输出
代码实现:
package reflect
import (
"reflect"
"errors"
"strconv"
)
// 数组切⽚求和
func ArraySum(input interface{}) (sum float64, err error) {
list := reflect.ValueOf(input)
switch reflect.TypeOf(input).Kind() {
case reflect.Slice, reflect.Array:
for i := 0; i < list.Len(); i++ {
val := list.Index(i)
v, err := toFloat64(val.Interface())
if err != nil {
return 0, err
}
sum += v
}
default:
return 0, errors.New("input must be slice or array")
}
return
}
func toFloat64(in interface{}) (f64 float64, err error) {
switch val := in.(type) {
case float64:
return val, nil
case float32:
return float64(val), nil
case uint8:
return float64(val), nil
case uint16:
return float64(val), nil
case uint32:
return float64(val), nil
case uint64:
return float64(val), nil
case uint:
if strconv.IntSize == 32 || strconv.IntSize == 64 {
return float64(val), nil
}
return 0, errors.New("convert uint to float64 failed")
case int8:
return float64(val), nil
case int16:
return float64(val), nil
case int32:
return float64(val), nil
case int64:
return float64(val), nil
case int:
if strconv.IntSize == 32 || strconv.IntSize == 64 {
return float64(val), nil
}
return 0, errors.New("convert int to float64 failed")
case bool:
if val {
f64 = 1
}
return
case string:
f64, err = strconv.ParseFloat(val, 64)
if err == nil {
return
}
return 0, errors.New("convert string to float64 failed")    default:
return 0, errors.New("convert to float64 failed")
}
}
测试:
func TestArraySum(t *testing.T) {
numberInt := []int{1,2,3,4}
val, err := ArraySum(numberInt)
fmt.Println(val, err)
numberStr := []string{"1","2","3","4"}
val, err = ArraySum(numberStr)
fmt.Println(val, err)
}
测试结果:
10 <nil>
10 <nil>
typeof array

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。