How to Convert Byte Slice to String in Go

Use the built-in `string()` type conversion to transform a byte slice into a string, as Go treats strings as immutable byte slices under the hood.

Use the built-in string() type conversion to transform a byte slice into a string, as Go treats strings as immutable byte slices under the hood. This operation is efficient because it does not allocate a new buffer if the byte slice is already backed by a string, though it may create a copy if the slice is mutable.

For standard ASCII or UTF-8 encoded data, a direct cast is the idiomatic approach:

package main

import "fmt"

func main() {
    // A byte slice containing UTF-8 encoded text
    b := []byte("Hello, Go!")
    
    // Direct conversion
    s := string(b)
    
    fmt.Println(s) // Output: Hello, Go!
}

If you are working with raw bytes from a network stream or file and need to ensure the data is valid UTF-8 before converting, use utf8.Valid to check validity first. This prevents creating strings containing invalid Unicode sequences, which can cause issues later in your application:

package main

import (
    "fmt"
    "unicode/utf8"
)

func safeConvert(b []byte) string {
    if utf8.Valid(b) {
        return string(b)
    }
    // Handle invalid UTF-8 (e.g., return empty string or log error)
    return ""
}

func main() {
    validBytes := []byte("Valid UTF-8")
    invalidBytes := []byte{0xFF, 0xFE} // Invalid UTF-8 sequence

    fmt.Println(safeConvert(validBytes))   // Output: Valid UTF-8
    fmt.Println(safeConvert(invalidBytes)) // Output: (empty string)
}

Avoid using string(b) on byte slices that might be modified later, as the resulting string shares the underlying memory with the slice in some Go versions (though this behavior is implementation-dependent and not guaranteed). If you need a completely independent copy, ensure the slice is not mutated after conversion or explicitly copy the data. For high-performance scenarios involving large binary data that isn't text, consider keeping it as a []byte rather than converting to a string, as string operations assume text semantics and may trigger unnecessary checks.