Golang:如何将一个由字符串和数字组成的整数数组求和

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

Golang: how to sum an array of integers as strings and numbers

问题

如何在GoLang中对包含字符串和数字混合类型的整数数组求和?

下面的代码出现错误:"mismatched types int and any" 和 "cannot initialize 1 variables with 2 values"。

是否有类似JavaScript解决方案的方法?
https://stackoverflow.com/questions/57893236/function-that-sums-array-numbers-including-numbers-as-strings

错误的代码:

  1. import (
  2. "fmt"
  3. "strconv"
  4. )
  5. func main() {
  6. fmt.Println(sum([]any{9, 1, "8", "2"})) // 这应该输出20
  7. }
  8. func sum(arr []any) int {
  9. n:=0
  10. for _, v := range arr{
  11. temp:=strconv.Atoi(v) // 错误:无法用2个值初始化1个变量
  12. n+=temp // 错误:类型不匹配 int 和 any
  13. }
  14. return n
  15. }

这个也会出错:

  1. n:=0
  2. for _, v := range arr{
  3. temp:=0
  4. if reflect.TypeOf(v)=="string"{
  5. temp=strconv.Atoi(v)
  6. } else {
  7. temp=v
  8. }
  9. n+=temp
  10. }
  11. return n
英文:

How to sum an array of integers with mixed types of strings and numbers in GoLang?
Code below errors with "mismatched types int and any" and "cannot initialize 1 variables with 2 values".

Is there something like this JavaScript solution?
https://stackoverflow.com/questions/57893236/function-that-sums-array-numbers-including-numbers-as-strings

errored code:

  1. import (
  2. "fmt"
  3. "strconv"
  4. )
  5. func main() {
  6. fmt.Println(sum([]any{9, 1, "8", "2"})) // this should output 20
  7. }
  8. func sum(arr []any) int {
  9. n:=0
  10. for _, v := range arr{
  11. temp:=strconv.Atoi(v) //err: cannot initialize 1 variables with 2 values
  12. n+=temp //err: mismatched types int and any
  13. }
  14. return n
  15. }

This also errors:

  1. n:=0
  2. for _, v := range arr{
  3. temp:=0
  4. if reflect.TypeOf(v)=="string"{
  5. temp=strconv.Atoi(v)
  6. } else {
  7. temp=v
  8. }
  9. n+=temp
  10. }
  11. return n
  12. </details>
  13. # 答案1
  14. **得分**: 4
  15. 使用[type switch](https://go.dev/ref/spec#Type_switches)来适当处理整数和字符串值。
  16. `temp:=strconv.Atoi(v)`返回两个值。将结果分配给两个变量。处理错误返回。
  17. 以下是修复后的代码:
  18. ```go
  19. func sum(arr []any) int {
  20. n := 0
  21. for _, v := range arr {
  22. switch v := v.(type) {
  23. case int:
  24. n += v
  25. case string:
  26. i, err := strconv.Atoi(v)
  27. if err != nil {
  28. panic(err)
  29. }
  30. n += i
  31. default:
  32. panic(fmt.Sprintf("unsupported type %T", v))
  33. }
  34. }
  35. return n
  36. }

为了完整起见,这里还有一个使用反射的版本的函数。但是,推荐使用类型切换版本的函数。

  1. func sum(arr []any) int {
  2. n := 0
  3. for _, v := range arr {
  4. v := reflect.ValueOf(v)
  5. if v.Kind() == reflect.Int {
  6. n += int(v.Int())
  7. } else if v.Kind() == reflect.String {
  8. i, err := strconv.Atoi(v.String())
  9. if err != nil {
  10. panic(err)
  11. }
  12. n += i
  13. } else {
  14. panic(fmt.Sprintf("unsupported type %s", v.Type()))
  15. }
  16. }
  17. return n
  18. }
英文:

> count+=temp //err: mismatched types int and any

Use a type switch to handle integer and string values as appropriate.

> temp:=strconv.Atoi(v) //err: cannot initialize 1 variables with 2 values

strconv.Atoi returns two values. Assign the result to two variables. Handle the error return.

Here's the code with the fixes:

  1. func sum(arr []any) int {
  2. n := 0
  3. for _, v := range arr {
  4. switch v := v.(type) {
  5. case int:
  6. n += v
  7. case string:
  8. i, err := strconv.Atoi(v)
  9. if err != nil {
  10. panic(err)
  11. }
  12. n += i
  13. default:
  14. panic(fmt.Sprintf(&quot;unsupported type %T&quot;, v))
  15. }
  16. }
  17. return n
  18. }

For completeness, here's a version of the function that uses reflection. The type switch version of the function is preferred over reflection.

  1. func sum(arr []any) int {
  2. n := 0
  3. for _, v := range arr {
  4. v := reflect.ValueOf(v)
  5. if v.Kind() == reflect.Int {
  6. n += int(v.Int())
  7. } else if v.Kind() == reflect.String {
  8. i, err := strconv.Atoi(v.String())
  9. if err != nil {
  10. panic(err)
  11. }
  12. n += i
  13. } else {
  14. panic(fmt.Sprintf(&quot;unsupported type %s&quot;, v.Type()))
  15. }
  16. }
  17. return n
  18. }

huangapple
  • 本文由 发表于 2022年10月31日 09:02:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/74257846.html
匿名

发表评论

匿名网友

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

确定