Golang: Curious Case of Returning Byte Array and Conversion to Byte Slice
For this article, just want to highlight a peculiar way to return byte array. Looking a the returnByteArray() function, notice that the return type is actually a concrete “array”. To return it, you can use copy (an in-built) function to copy over content to your array. Then return “empty”.
package mainimport (
"fmt"
)func returnByteArray() (array [5]byte) {byteSlice := []byte("Loves you")
copy(array[:], byteSlice[0:5])
return
}func main() {
byteArray := returnByteArray()
fmt.Println(string(byteArray[:])) // convert byte array to byte slice and string}
From the main program, you also can see how to use the byteArray[:] to convert back to a byteSlice. Out of the program is as follows:
$ go run main.go
Loves
Of course, you can use the usual syntax. See returnByteArrayUsual() and things will work fine.
package mainimport (
"fmt"
)func returnByteArray() (array [5]byte) {byteSlice := []byte("Loves you")
copy(array[:], byteSlice[0:5])
return
}func returnByteArrayUsual() [5]byte {
byteSlice := []byte("Loves you")
var array [5]byte
copy(array[:], byteSlice[0:5])
return array
}func main() {
byteArray := returnByteArray()
fmt.Println(string(byteArray[:])) // convert byte array to byte slice and stringbyteArray = returnByteArrayUsual()
fmt.Println(string(byteArray[:])) // convert byte array to byte slice and string}