Home »
Golang »
Golang Programs
How to convert a string to a byte slice in Golang?
Given a string, we have to convert the given string to a byte slice using syscall in Golang.
Submitted by IncludeHelp, on November 12, 2021 [Last updated : March 05, 2023]
Converting a string to a byte slice in Golang
In the Go language, to convert a string to a byte slice – we use the ByteSliceFromString() function of the syscall package. The ByteSliceFromString() function returns a NUL-terminated slice of bytes containing the text of s. If s contains a NUL byte at any location, it returns (nil, EINVAL).
Syntax
func ByteSliceFromString(s string) ([]byte, error)
Consider the below example demonstrating how to convert a string to a byte slice in Golang?
Golang code to convert a string to a byte slice
package main
import (
"fmt"
"syscall"
)
func main() {
str := "Hello, World!"
// Converting string to byte slice
ByteSlice, Err := syscall.ByteSliceFromString(str)
// Printing the type and value
fmt.Printf("ByteSlice: %T, %v\n", ByteSlice, ByteSlice)
// Printing the ERR
fmt.Printf("Err: %v\n", Err)
}
Output
ByteSlice: []uint8, [72 101 108 108 111 44 32 87 111 114 108 100 33 0]
Err: <nil>
Golang syscall Package Programs »