Home >Backend Development >Golang >golang map to byte
In Golang development, we often need to convert a map
into a byte
array (i.e. serialization). This could be because the map
needs to be passed to a network request, stored in a database, or interacted with other systems. This article will introduce how to convert map
to byte
array in Golang.
In Golang, we can use the Marshal
function provided by the standard library encoding/json
to map
Serialized into a byte
array. Marshal
The function receives a interface{}
type of data and can convert map
to a byte
array.
The following is a simple sample code:
package main import ( "encoding/json" "fmt" ) func main() { m := make(map[string]interface{}) m["name"] = "Alice" m["age"] = 20 m["gender"] = "female" // 序列化 map b, err := json.Marshal(m) if err != nil { fmt.Println("Error:", err) return } fmt.Println(string(b)) }
The above code will output the following string:
{"age":20,"gender":"female","name":"Alice"}
In addition to JSON, Golang Gob serialization is also provided. Gob serialization is different from JSON, it is the serialization format used internally by Golang. It's more efficient, but only Golang can understand it. Therefore, you need to pay attention when using it.
The following is a simple Gob serialization example:
package main import ( "bytes" "encoding/gob" "fmt" ) func main() { var buf bytes.Buffer enc := gob.NewEncoder(&buf) m := make(map[string]interface{}) m["name"] = "Alice" m["age"] = 20 m["gender"] = "female" // 序列化 map if err := enc.Encode(m); err != nil { fmt.Println("Error:", err) return } b := buf.Bytes() fmt.Println(b) }
This will output a byte array representing the serialized map
.
In Golang, we can use the encoding/json
or encoding/gob
library to map
sequence Convert to byte
array. Using JSON serialization can serialize map
into an easy-to-read string, while Gob serialization can gain advantages in efficiency. Just choose the appropriate serialization method according to your needs.
The above is the detailed content of golang map to byte. For more information, please follow other related articles on the PHP Chinese website!