0
0
GoHow-ToBeginner · 2 min read

Go: How to Convert String to Byte Slice Easily

In Go, you can convert a string to a byte slice by using a simple type conversion like []byte(yourString) which creates a new byte slice containing the string's bytes.
📋

Examples

Input"hello"
Output[104 101 108 108 111]
Input"GoLang"
Output[71 111 108 97 110 103]
Input""
Output[]
🧠

How to Think About It

To convert a string to a byte slice in Go, think of the string as a sequence of characters stored as bytes. You want to create a new slice that holds these bytes. Using []byte(yourString) tells Go to copy the string's bytes into a new slice, making it easy to work with the raw data.
📐

Algorithm

1
Take the input string.
2
Use the conversion syntax <code>[]byte(inputString)</code> to create a byte slice.
3
Return or use the resulting byte slice.
💻

Code

go
package main

import "fmt"

func main() {
    str := "hello"
    bytes := []byte(str)
    fmt.Println(bytes)
}
Output
[104 101 108 108 111]
🔍

Dry Run

Let's trace converting the string "hello" to a byte slice.

1

Input string

str = "hello"

2

Convert to byte slice

bytes = []byte(str) => [104 101 108 108 111]

3

Print result

Output: [104 101 108 108 111]

StepValue
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

Using copy with a pre-allocated slice
go
package main

import "fmt"

func main() {
    str := "hello"
    bytes := make([]byte, len(str))
    copy(bytes, str)
    fmt.Println(bytes)
}
This method manually copies bytes and can be useful if you want to reuse a slice, but it's more verbose than direct conversion.

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.

ApproachTimeSpaceBest For
Direct conversion []byte(str)O(n)O(n)Simple and fast conversion
Manual copy with make and copyO(n)O(n)Reusing slices or custom copying
💡
Use []byte(yourString) for a quick and easy conversion from string to byte slice.
⚠️
Trying to assign a string directly to a byte slice variable without conversion causes a compile error.