乐闻世界logo
搜索文章和话题

How to assign string to bytes array

1个答案

1

In Go, you can convert a string to a byte array by casting it to the []byte type. This can be done with a simple type conversion. Here is an example of converting a string to a byte array:

go
package main import ( "fmt" ) func main() { // Define a string str := "Hello, World!" // Convert the string to a byte array byteArray := []byte(str) // Print the byte array fmt.Printf("%v\n", byteArray) // Print the byte array as a string to display its content fmt.Printf("%s\n", byteArray) }

In this example, the string "Hello, World!" is converted to a byte array byteArray. The fmt.Printf function first prints the byte array in its raw form, then prints it as a string to verify the conversion was successful.

This process actually creates a copy of the string content and stores it as a byte array. Since strings in Go are immutable, this conversion allows you to modify the resulting byte array when needed.

Note that the conversion from string to byte array takes into account the string's encoding. In Go, the default string encoding is UTF-8, so if the string contains non-ASCII characters, the resulting byte array will contain the corresponding UTF-8 encoded bytes.

2024年6月29日 12:07 回复

你的答案