How to convert a string to a rune slice (UTF-32) using strconv in Golang?

To convert a string to a rune slice (UTF-32) using the strconv package in Golang, you can follow these steps:

  1. Import the strconv and unicode/utf8 packages:
import ( "strconv" "unicode/utf8" )
  1. Define the string you want to convert:
str := "Hello, 世界"
  1. Calculate the length of the string in bytes:
strLen := len(str)
  1. Create an empty rune slice with a capacity equal to the number of characters in the string:
runes := make([]rune, 0, utf8.RuneCountInString(str))
  1. Iterate through the string byte by byte using a for loop:
for i := 0; i < strLen; { r, size := utf8.DecodeRuneInString(str[i:]) // Add the decoded rune to the rune slice runes = append(runes, r) // Move to the next byte i += size }
  1. At this point, runes will contain the UTF-32 representation of the string. You can print it for verification:
fmt.Println(runes)

The complete code:

package main import ( "fmt" "strconv" "unicode/utf8" ) func main() { str := "Hello, 世界" strLen := len(str) runes := make([]rune, 0, utf8.RuneCountInString(str)) for i := 0; i < strLen; { r, size := utf8.DecodeRuneInString(str[i:]) runes = append(runes, r) i += size } fmt.Println(runes) }

This code will convert the string "Hello, 世界" to a rune slice [72 101 108 108 111 44 32 19990 30028].