将[]字符串转换为[]字节 [英] Convert []string to []byte

查看:153
本文介绍了将[]字符串转换为[]字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我期待在GO中将字符串数组转换为字节数组,以便我可以将其写入磁盘。什么是将字符串数组( [] string )编码和解码为字节数组( [] byte )?

我正在考虑迭代字符串数组两次,第一次是获取字节数组所需的实际大小,然后是第二次写入长度和实际字符串 [] byte(str))。

解决方案必须能够将其转换为另一个元素,办法;从 [] byte []字符串

解决方案

让我们忽略这是Go的事实。首先你需要的是一个序列化格式来编组 []字符串



这里有很多选项。你可以建立你自己的或使用图书馆。我会假设你不想自己创建并跳转到支持的序列化格式。

在所有示例中,数据都是 [] string ,fp是您正在读取/写入的文件。错误被忽略,请检查函数的返回值以处理错误。



Gob



二进制格式。它应该是相对空间有效的,因为字符串的数量增加。

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

阅读也很简单

  var data []字符串
dec:= gob.NewDecoder(fp)
dec.Decode(& data)

Gob简单明了。然而,格式只能用其他Go代码读取。下一个是json。 Json是一种无处不在的格式。

  enc:= json.NewEncoder(fp)
enc.Encode(数据)

阅读:

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



XML



XML是另一种常见格式。然而,它有相当高的开销,并不容易使用。虽然你可以像做gob和json一样做,但正确的xml需要一个根标签。在这种情况下,我们使用根标签Strings,每个字符串都包装在一个S标签中。

  type字符串struct {
S [] string
}

enc:= xml.NewEncoder(fp)
enc.Encode(String {data})

var x字符串
dec:= xml.NewDecoder(fp)
dec.Decode(& x)
data:= xS



CSV



CSV与其他不同。你有两个选择,使用一行记录n行或n记录1行。以下示例使用n个记录。如果我使用一个记录,那将是无聊的。它看起来太像其他人了。 CSV只能保存字符串。

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

阅读:

  var err错误
var数据字符串
dec:= csv.NewReader(fp)
for err == nil {//当达到错误时读取结束(可能是io.EOF)
var s []字符串

s,err = dec.Read()
if len(s)> 0 {
data = append(data,s [0])
}
}






您使用哪种格式是偏好问题。还有许多其他可能的编码,我没有提到。例如,有一个名为bencode的外部库。我个人不喜欢bencode,但它的工作原理。它与Bittorrent元数据文件使用的是相同的编码。



如果您想制作自己的编码,encoding / binary是一个很好的开始。这可以让你制作出最紧凑的文件,但我很难做出努力。


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.

解决方案

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.

这篇关于将[]字符串转换为[]字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆