skip to content
Alvin Lucillo

Safe UTF-8 decoding via loop in Go

/ 1 min read

💻 Tech

To safely and correctly decode a UTF-8 string via a loop, you can do it in two ways:

  1. Using for..range loop
s := "Hello"
for _, r := range s {
    fmt.Printf("%c", r)
}

// Output: Hello

For..range already handles UTF-8 values with runes that have a variable length.

  1. Using utf8.DecodeRuneInString function
s := "Hello"
for i := 0; i < len(s); i++ {
    r, size := utf8.DecodeRuneInString(s)
    if size > 1 {
        i += size - 1 // Skip the rest of the bytes of the character since it's already read
    }
    fmt.Printf("%c", r)
}

// Output: Hello