In Go, you can encode and decode structs to/from MessagePack using the `github.com/vmihailenco/msgpack` package. This package provides easy serialization and deserialization of Go data structures into the MessagePack format, which is efficient for both size and speed.
Below is an example of how to encode and decode a struct using MessagePack in Go:
package main
import (
"bytes"
"fmt"
"github.com/vmihailenco/msgpack/v5"
)
// Define a struct
type Person struct {
Name string `msgpack:"name"`
Age int `msgpack:"age"`
}
func main() {
// Create an instance of the struct
person := Person{Name: "Alice", Age: 30}
// Encode the struct to MessagePack
var buf bytes.Buffer
encoder := msgpack.NewEncoder(&buf)
err := encoder.Encode(person)
if err != nil {
fmt.Println("Encode error:", err)
return
}
// Decode the struct from MessagePack
var decodedPerson Person
decoder := msgpack.NewDecoder(&buf)
err = decoder.Decode(&decodedPerson)
if err != nil {
fmt.Println("Decode error:", err)
return
}
// Display the result
fmt.Printf("Decoded Person: %+v\n", decodedPerson)
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?