Home > Article > Backend Development > How to Convert an Arbitrary Go Interface to a Byte Array?
Creating a hash function that accepts any data type requires the ability to convert the data to a byte array. However, the binary package seems to demand knowledge of the data's type and byte order, making a simple conversion challenging.
The error was in the initial approach. The gob package is capable of handling this conversion effectively.
The following code shows how to convert an arbitrary interface{} to a byte array:
package bloom import ( "encoding/gob" "bytes" ) // GetBytes converts an interface{} to a byte array. func GetBytes(key interface{}) ([]byte, error) { var buf bytes.Buffer enc := gob.NewEncoder(&buf) err := enc.Encode(key) if err != nil { return nil, err } return buf.Bytes(), nil }
This function utilizes the gob package to encode the input interface into a byte array. It then returns the resulting byte array along with any errors encountered during encoding.
The above is the detailed content of How to Convert an Arbitrary Go Interface to a Byte Array?. For more information, please follow other related articles on the PHP Chinese website!