BudiBadu Logo

Samplebadu

Code with Example
BudiBadu Logo
Samplebadu

Go by Example: Byte Handling

Go 1.23

Bytes are the fundamental unit of data in Go. This example explores the `byte` alias, `[]byte` slices for mutable data, and how to efficiently convert between strings and bytes using the `bytes` package.

Code

package main

import (
    "bytes"
    "fmt"
)

func main() {
    // 1. The 'byte' alias
    // 'byte' is exactly the same as 'uint8'.
    var b byte = 65 // ASCII for 'A'
    fmt.Printf("Byte: %d, Character: %c\n", b, b)

    // 2. Byte Slices ([]byte)
    // Unlike strings, byte slices are mutable.
    data := []byte("Hello")
    data[0] = 'J' // Change 'H' to 'J'
    fmt.Println("Modified slice:", string(data))

    // 3. String <-> Byte Conversion
    // Converting creates a copy of the data (memory allocation).
    str := "Go"
    byteSlice := []byte(str)
    byteSlice[0] = 'N'
    
    fmt.Println("Original string:", str)       // "Go" (immutable)
    fmt.Println("Converted slice:", string(byteSlice)) // "No"

    // 4. Using bytes.Buffer
    // Efficient way to build strings or byte arrays (like StringBuilder).
    var buf bytes.Buffer
    buf.WriteString("Hello")
    buf.WriteByte(',')
    buf.WriteString(" World!")
    
    fmt.Println("Buffer result:", buf.String())
    
    // 5. Common bytes package functions
    // The 'bytes' package is like 'strings' but for []byte.
    src := []byte("go programming")
    upper := bytes.ToUpper(src)
    fmt.Printf("Upper: %s\n", upper)
}

Explanation

In Go, a byte is an alias for uint8. It represents a single byte of data (0-255). While strings are used for text, []byte (byte slice) is the standard type for raw binary data, network streams, and file I/O.

The key difference is mutability: strings are immutable (cannot be changed once created), whereas byte slices are mutable. This makes []byte essential when you need to modify data in place. Converting between string and []byte is easy (`[]byte(str)` and `string(bytes)`), but be aware that it typically causes a memory allocation because the data must be copied to ensure safety.

For efficient manipulation, the standard library provides the bytes package. It includes a Buffer type (similar to StringBuilder in Java/C#) which is highly recommended for concatenating strings or bytes to avoid unnecessary allocations.

  • Alias: byte == uint8.
  • Mutability: Strings are read-only; byte slices are read-write.
  • Conversion: []byte("text") copies memory.
  • Performance: Use bytes.Buffer for building large strings.

Code Breakdown

10-11
Declaring a byte. Since it's just a number (uint8), we can assign 65 to it. When printed with %c, it displays the corresponding ASCII character 'A'.
15-17
Demonstrating mutability. We create a slice from "Hello", then change the first byte to 'J'. This operation is impossible with a standard string variable.
30-35
Using bytes.Buffer. This is the idiomatic way to construct strings efficiently. It manages an internal slice that grows as needed, minimizing memory churn compared to using the '+' operator in a loop.
40
bytes.ToUpper works exactly like strings.ToUpper, but on a byte slice. The bytes package mirrors most of the strings package's functionality.