ADVERTISEMENT
ADVERTISEMENT

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

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?

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 »



ADVERTISEMENT




ADVERTISEMENT



Comments and Discussions!

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.