In Go, strings are immutable sequences of bytes, and byte arrays represent a contiguous memory block of bytes. Assigning a string to a byte array involves converting the string into its byte representation. In this blog post, we’ll explore different methods to achieve this conversion in Go.

Method 1: Using []byte() Conversion

The simplest and most direct way to convert a string to a byte array is by using a type conversion with []byte().

package main

import "fmt"

func main() {
    // Assigning a string to a byte array using []byte()
    str := "Hello, Go!"
    byteArray := []byte(str)

    // Print the byte array
    fmt.Println(byteArray)
}

OUTPUT
[72 101 108 108 111 44 32 71 111 33]

In this example, []byte(str) converts the string str into a byte array. Each character in the string corresponds to a byte in the resulting array.

Method 2: Using []byte Type Casting

Another approach to convert a string to a byte array involves directly assigning the string to a byte array variable using type casting.

package main

import "fmt"

func main() {
    // Assigning a string to a byte array using type casting
    var byteArray [len("Hello, Go!")]byte
    copy(byteArray[:], "Hello, Go!")

    // Print the byte array
    fmt.Println(byteArray)
}

OUTPUT
[72 101 108 108 111 44 32 71 111 33]

In this example, a byte array byteArray of the same length as the string is created. The copy() function is used to copy the bytes from the string to the byte array.

Method 3: Using strconv Package

If you want to work with the string at a character level and convert each character to its corresponding byte, you can use the strconv package along with strconv.QuoteToASCII().

package main

import (
    "fmt"
    "strconv"
)

func main() {
    // Assigning a string to a byte array using strconv.QuoteToASCII()
    str := "Hello, Go!"
    quoted := strconv.QuoteToASCII(str)
    byteArray := []byte(quoted[1 : len(quoted)-1])

    // Print the byte array
    fmt.Println(byteArray)
}

OUTPUT
[72 101 108 108 111 44 32 71 111 33]

In this example, strconv.QuoteToASCII() returns a double-quoted Go string literal representation of the string, which includes escape sequences for non-printable characters. Trimming the quotes with slicing and converting the resulting string to a byte array yields the desired output.

Conclusion

Converting a string to a byte array in Go involves interpreting the string’s characters as bytes. The methods described above allow you to perform this conversion efficiently. Depending on your specific use case and requirements, choose the method that best suits your needs for working with strings as byte arrays in your Go programs.

Support On Demand!

Golang