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.

Leave a Comment