Golang : Convert []string to []byte examples
Problem :
You need a fast way to convert a []string to []byte type. To use in situations such as storing text data into a random access file or other type of data manipulation that requires the input data to be in []byte type.
Solutions :
Example 1:
package main
import (
"fmt"
"strings"
)
func main() {
stringSlice := []string{"hello", "bye"}
stringByte := "\x00" + strings.Join(stringSlice, "\x20\x00") // x20 = space and x00 = null
fmt.Println([]byte(stringByte))
fmt.Println(string([]byte(stringByte)))
}
Output :
[0 104 101 108 108 111 32 0 98 121 101]
hello bye
Example 2:
package main
import (
"bytes"
"encoding/gob"
"fmt"
)
func main() {
stringSlice := []string{"hello", "bye"}
buffer := &bytes.Buffer{}
gob.NewEncoder(buffer).Encode(stringSlice)
byteSlice := buffer.Bytes()
fmt.Printf("%q\n", byteSlice)
fmt.Println("---------------------------")
backToStringSlice := []string{}
gob.NewDecoder(buffer).Decode(&backToStringSlice)
fmt.Printf("%v\n", backToStringSlice)
}
Output :
[12 255 129 2 1 2 255 130 0 1 12 0 0 14 255 130 0 2 5 104 101 108 108 111 3 98 121 101]
[hello bye]
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+5.8k AWS S3 : Prevent Hotlinking policy
+9.1k Golang : How to control fmt or log print format?
+32.1k Golang : Convert []string to []byte examples
+5.9k Golang : Grab news article text and use NLP to get each paragraph's sentences
+29.7k Golang : Get time.Duration in year, month, week or day
+19.8k Golang : Convert(cast) bytes.Buffer or bytes.NewBuffer type to io.Reader
+7.4k Golang : Detect sample rate, channels or latency with PortAudio
+5.5k Golang : Frobnicate or tweaking a string example
+7.8k Javascript : Put image into Chrome browser's console
+13.8k Golang : How to check if a file is hidden?
+15.4k Golang : Force download file example
+9.6k Golang : List available AWS regions