Convert []string to []byte

后端 未结 6 1592
梦谈多话
梦谈多话 2021-02-07 01:36

I am looking to convert a string array to a byte array in GO so I can write it down to a disk. What is an optimal solution to encode and decode a string array ([]string

6条回答
  •  时光说笑
    2021-02-07 02:28

    The gob package will do this for you http://godoc.org/encoding/gob

    Example to play with http://play.golang.org/p/e0FEZm-qiS

    same source code is below.

    package main
    
    import (
        "bytes"
        "encoding/gob"
        "fmt"
    )
    
    func main() {
        // store to byte array
        strs := []string{"foo", "bar"}
        buf := &bytes.Buffer{}
        gob.NewEncoder(buf).Encode(strs)
        bs := buf.Bytes()
        fmt.Printf("%q", bs)
    
        // Decode it back
        strs2 := []string{}
        gob.NewDecoder(buf).Decode(&strs2)
        fmt.Printf("%v", strs2)
    }
    

提交回复
热议问题