Sobes.tech
Senior

What happens to a string when reversed by bytes and by runes? What problems can you encounter?

sobes.tech AI

Answer from AI

Reversing a string by bytes in Go changes the byte order, but if the string contains multi-byte UTF-8 characters (runes), such characters can be corrupted because the character's bytes will be in the wrong order. As a result, the string becomes invalid and may cause errors during output or processing.

Reversing by runes (Unicode code points) changes the order of characters, not bytes, which preserves the correctness of UTF-8 encoding. This is the correct way to reverse strings with multi-byte characters.

Problems:

  • Byte-wise reversal breaks multi-byte characters.
  • It should be considered that a rune is not always a single visual character (for example, emojis with modifiers), so a simple rune reversal may change the visual representation.

Example of reversing by runes in Go:

func reverseRunes(s string) string {
    runes := []rune(s)
    for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
        runes[i], runes[j] = runes[j], runes[i]
    }
    return string(runes)
}