登录
首页 >  Golang >  Go问答

Golang:使用整数数组进行字符串与数字求和的方法

来源:stackoverflow

时间:2024-02-11 11:54:23 108浏览 收藏

小伙伴们有没有觉得学习Golang很有意思?有意思就对了!今天就给大家带来《Golang:使用整数数组进行字符串与数字求和的方法》,以下内容将会涉及到,若是在学习中对其中部分知识点有疑问,或许看了本文就能帮到你!

问题内容

如何在 golang 中对字符串和数字混合类型的整数数组求和? 下面的代码错误“int 和 any 类型不匹配”和“无法用 2 个值初始化 1 个变量”。

有类似 javascript 的解决方案吗? 对数组数字(包括作为字符串的数字)求和的函数

错误代码:

import (
"fmt"
"strconv"
)

func main() {
  fmt.println(sum([]any{9, 1, "8", "2"})) // this should output 20
}

func sum(arr []any) int {
  n:=0
  for _, v := range arr{
    temp:=strconv.atoi(v) //err: cannot initialize 1 variables with 2 values
    n+=temp //err: mismatched types int and any
  }
  return n
}

这也会错误:

n:=0
  for _, v := range arr{
    temp:=0
    if reflect.TypeOf(v)=="string"{
      temp=strconv.Atoi(v)
    } else {
      temp=v
    }
    n+=temp
  }
  return n

正确答案


使用 type switch 来处理适当的整数和字符串值。

strconv.Atoi 返回两个值。将结果分配给两个变量。处理错误返回。

以下是修复后的代码:

func sum(arr []any) int {
    n := 0
    for _, v := range arr {
        switch v := v.(type) {
        case int:
            n += v
        case string:
            i, err := strconv.atoi(v)
            if err != nil {
                panic(err)
            }
            n += i
        default:
            panic(fmt.sprintf("unsupported type %t", v))
        }
    }
    return n
}

为了完整起见,这里是使用反射的函数版本。该函数的类型开关版本优于反射。

func sum(arr []any) int {
    n := 0
    for _, v := range arr {
        v := reflect.ValueOf(v)
        if v.Kind() == reflect.Int {
            n += int(v.Int())
        } else if v.Kind() == reflect.String {
            i, err := strconv.Atoi(v.String())
            if err != nil {
                panic(err)
            }
            n += i
        } else {
            panic(fmt.Sprintf("unsupported type %s", v.Type()))
        }
    }
    return n
}

以上就是《Golang:使用整数数组进行字符串与数字求和的方法》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>