英文:
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
错误的代码:
import (
"fmt"
"strconv"
)
func main() {
fmt.Println(sum([]any{9, 1, "8", "2"})) // 这应该输出20
}
func sum(arr []any) int {
n:=0
for _, v := range arr{
temp:=strconv.Atoi(v) // 错误:无法用2个值初始化1个变量
n+=temp // 错误:类型不匹配 int 和 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
英文:
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:
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
}
This also errors:
n:=0
for _, v := range arr{
temp:=0
if reflect.TypeOf(v)=="string"{
temp=strconv.Atoi(v)
} else {
temp=v
}
n+=temp
}
return n
</details>
# 答案1
**得分**: 4
使用[type switch](https://go.dev/ref/spec#Type_switches)来适当处理整数和字符串值。
`temp:=strconv.Atoi(v)`返回两个值。将结果分配给两个变量。处理错误返回。
以下是修复后的代码:
```go
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
}
英文:
> 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:
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
}
For completeness, here's a version of the function that uses reflection. The type switch version of the function is preferred over reflection.
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论