The Go language implementation transforms []string into []byte

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

The Go language implementation transforms []string into []byte

Suppose you want to implement the conversion of the Go language string array to a byte array. The demo functions are as follows:

func convertStringsToBytes(){    stringContent := []string{"通知中心","perfect!"}    byteContent := "\x00"+ strings.Join(stringContent, "\x02\x00")  // x20 = space and x00 = null    fmt.Println([]byte(byteContent))    fmt.Println(string([]byte(byteContent)))}

Full code:

package main import (    "fmt"    "strings" ) func convert(){    stringSlice := []string{"通知中心","perfect!"}    stringByte := "\x00" + strings.Join(stringSlice, "\x20\x00") // x20 = space and x00 = null    fmt.Println([]byte(stringByte))    fmt.Println(string([]byte(stringByte))) } func main() {    convert() }

Operation Result:

[0 233 128 154 231 159 165 228 184 173 229 191 131 2 0 112 101 114 102 101 99 116 33] 通知中心  perfect!

This is the simplest method, and there is another way to achieve the same effect. It is primarily implemented using coding mechanisms.

 package main import (    "bytes"    "encoding/gob"    "fmt" )func convert(){    stringSlice := []string{"通知中心","perfect!"}    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)} func main() {    convert() }

Welcome you!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.