The Go language converts string to []byte

In Go language, there are two types that can store a string of characters, namely string and array of byte type []byte. However, they cannot be directly assigned with equal sign or simply converted. Instead, they need to be converted by slicing.

String is converted to []byte

The cast can be done directly using []byte(STR).

package main

import "fmt"

func main(a) {
	var str string = "test"
	var data []byte = []byte(str)
    fmt.Println("string: ", str)	// string: test
    fmt.Println("[]byte: ", data)	// []byte: [116 101 115 116]
}
Copy the code

You can see that []byte outputs the ASCII characters of the string.

[]byte converts to string

Converting a byte array to a string cannot be done directly, but requires a slice of []byte. That is, string(array name [:]) is used for the conversion.

package main

import "fmt"

func main(a) {
	var data [5]byte
	data[0] = 'T'
	data[1] = 'E'
	data[2] = 'S'
	data[3] = 'T'
	var str string = string(data[:])
	fmt.Println("[]byte: ", data)	// []byte: [84 69 83 84 0]
	fmt.Println("string: ", str)	// string: TEST
}
Copy the code

practice

Will [] [] byte type of two-dimensional array board, initialized to [[” A “, “B”, “C”, “E”], [” S “, “F”, “C”, “S”], [” A “, “D”, “E”, “E”]]

board := [][]byte{[]byte("ABCE"), []byte("SFCS"), []byte("ADEE")}
Copy the code

Because Go language requires all variables (including intermediate results) to have certain values, in the declaration process, (board[0])[], (board[1])[], (board[2])[] should be given certain values before board can be generated. Therefore, conversion should be carried out within the definition.