In Go, you can convert a set of strings to a set of integers by iterating through the set and using the strconv.Atoi() function to convert each string to an integer.
In this example,
package main
import (
"fmt"
"strconv"
)
func main() {
stringSet1 := map[string]struct{}{"1": {}, "2": {}, "3": {}, "4": {}, "5": {}}
intSet1 := make(map[int]struct{})
for str := range stringSet1 {
if i, err := strconv.Atoi(str); err == nil {
intSet1[i] = struct{}{}
}
}
fmt.Println(intSet1)
}
map[1:{} 2:{} 3:{} 4:{} 5:{}]
In this example,
package main
import (
"fmt"
"strconv"
)
func main() {
stringSet2 := map[string]struct{}{"10": {}, "20": {}, "30": {}, "40": {}, "50": {}}
intSet2 := make(map[int]struct{})
for str := range stringSet2 {
if i, err := strconv.ParseInt(str, 10, 64); err == nil {
intSet2[int(i)] = struct{}{}
}
}
fmt.Println(intSet2)
}
map[10:{} 20:{} 30:{} 40:{} 50:{}]
In this tutorial, we learned How to Convert a Set of Strings to a Set of Integers in Go language with well detailed examples.