Sobes.tech
Senior

Tell us about byte and rune in Go, what is the difference, and give an example with string reversal.

sobes.tech AI

Answer from AI

In Go, byte is an alias for uint8, used to represent a single byte of data, often for ASCII characters. rune is an alias for int32, representing a Unicode code point, i.e., a character in UTF-8 encoding.

The difference is that byte is just a byte, while rune is a character that can occupy multiple bytes in UTF-8.

Example of reversing a string considering Unicode:

package main

import "fmt"

func reverse(s string) string {
    runes := []rune(s) // convert string to a slice of runes
    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)
}

func main() {
    s := "Привет, мир!"
    fmt.Println(reverse(s)) // !рим ,тевирП
}

This way, we correctly handle multi-byte characters, unlike reversing by bytes, which can break UTF-8.

Tell us about byte and rune in Go, what is the… - sobes.tech