duande9301 2012-11-26 21:14
浏览 83
已采纳

将[]字符串转换为[]字节

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) to a byte array ([]byte)?

I was thinking of iterating the string array twice, first one to get the actual size needed for the byte array and then a second one to write the length and actual string ([]byte(str)) for each element.

The solution must be able to convert it the other-way; from a []byte to a []string.

  • 写回答

5条回答 默认 最新

  • doudian6229 2012-11-27 00:08
    关注

    Lets ignore the fact that this is Go for a second. The first thing you need is a serialization format to marshal the []string into.

    There are many option here. You could build your own or use a library. I am going to assume you don't want to build your own and jump to serialization formats go supports.

    In all examples, data is the []string and fp is the file you are reading/writing to. Errors are being ignored, check the returns of functions to handle errors.

    Gob

    Gob is a go only binary format. It should be relatively space efficient as the number of strings increases.

    enc := gob.NewEncoder(fp)
    enc.Encode(data)
    

    Reading is also simple

    var data []string
    dec := gob.NewDecoder(fp)
    dec.Decode(&data)
    

    Gob is simple and to the point. However, the format is only readable with other Go code.

    Json

    Next is json. Json is a format used just about everywhere. This format is just as easy to use.

    enc := json.NewEncoder(fp)
    enc.Encode(data)
    

    And for reading:

    var data []string
    dec := json.NewDecoder(fp)
    dec.Decode(&data)
    

    XML

    XML is another common format. However, it has pretty high overhead and not as easy to use. While you could just do the same you did for gob and json, proper xml requires a root tag. In this case, we are using the root tag "Strings" and each string is wrapped in an "S" tag.

    type Strings struct {
        S []string
    }
    
    enc := xml.NewEncoder(fp)
    enc.Encode(Strings{data})
    
    var x Strings
    dec := xml.NewDecoder(fp)
    dec.Decode(&x)
    data := x.S
    

    CSV

    CSV is different from the others. You have two options, use one record with n rows or n records with 1 row. The following example uses n records. It would be boring if I used one record. It would look too much like the others. CSV can ONLY hold strings.

    enc := csv.NewWriter(fp)
    for _, v := range data {
        enc.Write([]string{v})
    }
    enc.Flush()
    

    To read:

    var err error
    var data string
    dec := csv.NewReader(fp)
    for err == nil {        // reading ends when an error is reached (perhaps io.EOF)
        var s []string
    
        s, err = dec.Read()
        if len(s) > 0 {
            data = append(data, s[0])
        }
    }
    

    Which format you use is a matter of preference. There are many other possible encodings that I have not mentioned. For example, there is an external library called bencode. I don't personally like bencode, but it works. It is the same encoding used by bittorrent metadata files.

    If you want to make your own encoding, encoding/binary is a good place to start. That would allow you to make the most compact file possible, but I hardly thing it is worth the effort.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 请问如何在openpcdet上对KITTI数据集的测试集进行结果评估?
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错