如何将数组中的字符串转换为go中数组中的整数?
["1", "2", "3"]
至
[1, 2, 3]
I've searched for some solutions online but couldn't find it. I've tried 至 loop through the array and did strconv.ParseFloat(v, 64) where v is the value but it didn't work.
如何将数组中的字符串转换为go中数组中的整数?
["1", "2", "3"]
至
[1, 2, 3]
I've searched for some solutions online but couldn't find it. I've tried 至 loop through the array and did strconv.ParseFloat(v, 64) where v is the value but it didn't work.
你必须在切片中循环.如果切片只包含整数,那么不需要ParseFloat
、Atoi
就足够了.
import "fmt"
import "strconv"
func main() {
var t = []string{"1", "2", "3"}
var t2 = []int{}
for _, i := range t {
j, err := strconv.Atoi(i)
if err != nil {
panic(err)
}
t2 = append(t2, j)
}
fmt.Println(t2)
}
数到Playground.