Go: convert strings in array to integer
You will have to loop through the slice indeed. If the slice only contains integers, no need of ParseFloat
, Atoi
is sufficient.
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)
}
On Playground.
For example,
package main
import (
"fmt"
"strconv"
)
func sliceAtoi(sa []string) ([]int, error) {
si := make([]int, 0, len(sa))
for _, a := range sa {
i, err := strconv.Atoi(a)
if err != nil {
return si, err
}
si = append(si, i)
}
return si, nil
}
func main() {
sa := []string{"1", "2", "3"}
si, err := sliceAtoi(sa)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("%q %v\n", sa, si)
}
Output:
["1" "2" "3"] [1 2 3]
Playground:
http://play.golang.org/p/QwNO8R_f90