Introducing Radical.sh

Forget Code launches a powerful code generator for building API's

Convert string array to int array in Go

To convert an array of strings to an array of integers in Go, you can use a loop and the strconv.Atoi() function from the strconv package. Here's an example:

package main

import (
    "fmt"
    "strconv"
)

func main() {
    strArr := []string{"1", "2", "3", "4", "5"}
    intArr := make([]int, len(strArr))

    for i, s := range strArr {
        num, err := strconv.Atoi(s)
        if err != nil {
            fmt.Println("Error:", err)
            return
        }
        intArr[i] = num
    }

    fmt.Println(intArr)
}


In this example, we first define an array of strings strArr containing the numbers we want to convert. We then create an empty array of integers intArr with the same length as strArr.

We then loop through strArr using a for loop and the range keyword. For each string s, we call strconv.Atoi() function with s as the argument to convert it to an integer. If there is an error during the conversion, we print it to the console and exit the program using the return statement. Otherwise, we set the integer value to the corresponding index of intArr.

Finally, we print intArr to the console.