Cannot Assign String to Byte Slice

cannot use s (variable of type string) as type []byte in assignment

Quick Answer

Convert the string to a byte slice explicitly using []byte(s).

Why This Happens

Strings and byte slices are different types in Go, even though they hold similar data. Go does not implicitly convert between them. You need an explicit conversion with []byte(s) to go from string to bytes, or string(b) to go from bytes to string.

The Problem

func main() {
    var buf []byte
    buf = "hello" // cannot use string as []byte
}

The Fix

func main() {
    buf := []byte("hello")
    fmt.Println(buf)
}

Step-by-Step Fix

  1. 1

    Identify the assignment

    Find where a string is being assigned to a []byte variable or passed to a function expecting []byte.

  2. 2

    Add the conversion

    Wrap the string with []byte() for explicit conversion.

  3. 3

    Consider performance

    Each conversion copies the data. If performance matters, consider working with one type consistently.

Bugsly catches this automatically

Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.

Try Bugsly free