Go: How to Convert String to Byte Slice Easily
[]byte(yourString) which creates a new byte slice containing the string's bytes.Examples
How to Think About It
[]byte(yourString) tells Go to copy the string's bytes into a new slice, making it easy to work with the raw data.Algorithm
Code
package main import "fmt" func main() { str := "hello" bytes := []byte(str) fmt.Println(bytes) }
Dry Run
Let's trace converting the string "hello" to a byte slice.
Input string
str = "hello"
Convert to byte slice
bytes = []byte(str) => [104 101 108 108 111]
Print result
Output: [104 101 108 108 111]
| Step | Value |
|---|---|
| Input string | "hello" |
| Byte slice | [104 101 108 108 111] |
Why This Works
Step 1: String is a sequence of bytes
In Go, a string stores text as a sequence of bytes internally, so converting it to a byte slice means extracting those bytes.
Step 2: Type conversion creates a new slice
Using []byte(yourString) copies the bytes into a new slice, allowing you to modify or inspect the raw data.
Step 3: Result is a slice of bytes
The result is a slice of type []byte that holds the numeric byte values representing each character.
Alternative Approaches
package main import "fmt" func main() { str := "hello" bytes := make([]byte, len(str)) copy(bytes, str) fmt.Println(bytes) }
Complexity: O(n) time, O(n) space
Time Complexity
Converting a string to a byte slice requires copying each byte, so it takes time proportional to the string length.
Space Complexity
A new byte slice is created with the same length as the string, so space usage grows linearly with input size.
Which Approach is Fastest?
Direct conversion []byte(str) is simple and efficient; manual copying is more verbose and slightly slower.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Direct conversion []byte(str) | O(n) | O(n) | Simple and fast conversion |
| Manual copy with make and copy | O(n) | O(n) | Reusing slices or custom copying |
[]byte(yourString) for a quick and easy conversion from string to byte slice.