A slice is a descriptor of an array segment
It consists of
- a pointer to the array,
- the length of the segment, and
- its capacity (the maximum length of the segment)
Below, string Array/Slice is converted to int Array/Slice:
package main
import (
"fmt"
"log"
"strconv"
"strings"
)
func Slice_Atoi(strArr []string) ([]int, error) {
// NOTE: Read Arr as Slice as you like
var str string // O
var i int // O
var err error // O
iArr := make([]int, 0, len(strArr))
for _, str = range strArr {
i, err = strconv.Atoi(str)
if err != nil {
return nil, err // O
}
iArr = append(iArr, i)
}
return iArr, nil
}
func main() {
strArr := []string{
"0 0 24 3 15",
"0 0 2 5 1 5 11 13",
}
for i := 0; i < len(strArr); i++ {
iArr, err := Slice_Atoi(strings.Split(strArr[i], " "))
if err != nil {
log.Print("Slice_Atoi failed: ", err)
return
}
fmt.Println(iArr)
}
}
Output:
[0 0 24 3 15]
[0 0 2 5 1 5 11 13]
I used in a project, so did a small optimizations from other replies, marked as // O for above, also fixed a bit in readability for others
Best of luck