What is the difference between byte and rune in Go?

QuestionsQuestions8 SkillsProCharacter Types in GolangSep, 12 2025
0173

In Go, the main differences between byte and rune are:

  1. Type Definition:

    • byte is an alias for uint8, which means it occupies 1 byte (8 bits) and can represent values from 0 to 255. It is typically used for ASCII characters.
    • rune is an alias for int32, which means it occupies 4 bytes (32 bits) and can represent a wider range of characters, including Unicode characters.
  2. Character Representation:

    • byte is suitable for representing ASCII characters, which are limited to 128 characters.
    • rune is used for representing Unicode characters, allowing for a much larger set of characters, including emojis and characters from various languages.
  3. Usage:

    • Use byte when dealing with raw binary data or ASCII text.
    • Use rune when you need to handle Unicode text, such as characters from non-Latin scripts or special symbols.

Here’s a simple example to illustrate their usage:

package main

import "fmt"

func main() {
    var a byte = 'A' // ASCII character
    var b rune = '😊' // Unicode character (emoji)

    fmt.Printf("Byte value: %c\n", a) // Outputs: A
    fmt.Printf("Rune value: %c\n", b)  // Outputs: 😊
}

In summary, use byte for ASCII and rune for Unicode characters.

0 Comments

no data
Be the first to share your comment!