简体   繁体   中英

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

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 in Go are of fixed length, so calling append on them won't work. 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...

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.

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 .

However, this also has limitations, in that when serializing structs, it can only access exported fields, or those exposed through the GobEncoder interface. 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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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