How do I encode a struct to/from Protobuf in Go?

In Go, encoding and decoding structs to and from Protobuf (Protocol Buffers) can be accomplished using the `protobuf` package. Below is an example that illustrates how to create a struct, define a Protobuf message, and encode/decode the data.

// First, define your Protobuf message in a .proto file syntax = "proto3"; package example; message User { string name = 1; int32 age = 2; }
// Generating Go code with: protoc --go_out=. user.proto // Go struct package main import ( "fmt" "log" "google.golang.org/protobuf/proto" "path/to/generated/protobuf/package" // Adjust the import path ) func main() { // Create a new User instance user := &example.User{ Name: "John Doe", Age: 30, } // Marshal (encode) the struct to Protobuf data, err := proto.Marshal(user) if err != nil { log.Fatal("Marshaling error: ", err) } // Unmarshal (decode) the Protobuf data back to struct userUnmarshaled := &example.User{} err = proto.Unmarshal(data, userUnmarshaled) if err != nil { log.Fatal("Unmarshaling error: ", err) } fmt.Printf("User: %s, Age: %d\n", userUnmarshaled.Name, userUnmarshaled.Age) }

Go Protobuf encoding decoding struct Protocol Buffers Golang