Golang is a powerful programming language with many useful libraries and functions. One very useful feature is converting a string into a byte array. In this article, we will take a deep dive into how to convert a string to a byte array using Golang functions.
Golang provides several methods to convert strings to byte arrays. The most commonly used methods are to use the []byte function and []rune function. The two functions are defined as follows:
func []byte(s string) []byte func []rune(s string) []rune
[]byte
function converts a string to a byte array, while []rune
function converts a string to Unicode character array. Both functions will return a new byte array or character array containing a copy of the string passed in.
If you want to convert a string to a byte array, you can use the following code:
s := "Hello, World!" b := []byte(s) fmt.Printf("%v\n", b)
The output is:
[72 101 108 108 111 44 32 87 111 114 108 100 33]
This code snippet converts the string "Hello , World!" into a byte array and print it out. As can be seen, each character is converted to its ASCII value and stored in a byte array.
If you want to convert a string to a Unicode character array, you can use the following code:
s := "안녕하세요" r := []rune(s) fmt.Printf("%v\n", r)
The output result is:
[44032 45208 45796 54620]
This code snippet will convert a Korean string " 안녕하세요" into a character array and print it out. Each character corresponds to a Unicode code value and is stored in a character array.
It should be noted that the []rune
function only applies to Unicode characters. If the string only contains ASCII characters, you can use the []byte function.
In general, Golang's string to byte array function is easy to use, flexible and diverse. You can flexibly choose which method to use for conversion based on actual needs. Hope this article helps you!
The above is the detailed content of How to convert string to byte array (byte) in golang. For more information, please follow other related articles on the PHP Chinese website!