简体   繁体   English

如何将任何数据类型转换为 Go 中的字节

[英]How to convert any data type to a byte in Go

I am trying to make a for loop that will convert any data type to a byte array... this is what I have right now我正在尝试制作一个将任何数据类型转换为字节数组的 for 循环......这就是我现在所拥有的

var arrByte [][]byte
    for _,v := range *arr.(*[]interface{}) {
        string := fmt.Sprint(v)   // What can I put here so that I dont have to convert to string
        arrByte = append(arrByte, []byte(string))
    }

The problem with this code is that I cant convert it back to its data types.这段代码的问题是我无法将它转换回它的数据类型。 So how can I directly change it so that It keeps the formatting correct so then I can later run this?那么如何直接更改它以保持格式正确,以便我以后可以运行它?

var arrInterface []interface{}

    for _,v := range arrByte {
        data := binary.BigEndian.Uint64(v)
        arrInterface = append(arrInterface, data)
    }

First, a note on terminology: You appear to be talking about byte slices not byte arrays.首先,关于术语的注释:您似乎在谈论字节而不是字节 arrays。 Arrays in Go are of fixed length, so calling append on them won't work. Go 中的 Arrays 是固定长度的,因此在它们上调用append将不起作用。 See here for more.请参阅此处了解更多信息。

Now to your question...现在回答你的问题...

I am trying to make a for loop that will convert any data type to a byte array...我正在尝试制作一个 for 循环,它将任何数据类型转换为字节数组......

This is not possible, except in the most superficial, meaningless sense.这是不可能的,除非在最肤浅、毫无意义的意义上。 For example, if you have a variable of type net.Conn , converting it to bytes will give you a meaningless value, since it is only meaningful in conjunction with one specific, active network connection.例如,如果您有一个net.Conn类型的变量,将其转换为字节将给您一个无意义的值,因为它仅在与一个特定的活动网络连接结合使用时才有意义。

However, assuming you don't have variables that refer to ephemeral state like this, the simplest way to convert arbitrary variables into a byte slice is with something like gob encoding .但是,假设您没有像这样引用临时 state 的变量,将任意变量转换为字节切片的最简单方法是使用gob encoding之类的方法。

However, this also has limitations, in that when serializing structs, it can only access exported fields, or those exposed through the GobEncoder interface.但是,这也有局限性,在序列化结构时,它只能访问导出的字段,或者通过GobEncoder接口公开的字段。 This Q&A explains why this limitation exists .此问答解释了为什么存在此限制

Now, in some cases you can work around this limitation with reflection, for example, but doing so is very cumbersome, and is usually unwise, since unexported fields often reference ephemeral state (see the note above).现在,在某些情况下,您可以通过反射来解决此限制,但是这样做非常麻烦,而且通常是不明智的,因为未导出的字段通常引用临时 state(请参阅上面的注释)。

So in summary: It's impossible to meaningfully do this for all data types.总而言之:不可能对所有数据类型都有意义地执行此操作。 It's difficult to do it for many data types, and it's trivial to do it for "normal" data types.对于许多数据类型来说很难做到这一点,而对于“普通”数据类型来说做到这一点是微不足道的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM