package main import ( "bytes" "github.com/golang/protobuf/proto" ) func main() { str := "Hello, world!" buf := &bytes.Buffer{} err := proto.BufferEncodeStringBytes(buf, str) if err != nil { panic(err) } encoded := buf.Bytes() // Use encoded byte array }
package main import ( "bytes" "github.com/golang/protobuf/proto" "fmt" ) type User struct { Name string } func main() { u := User{Name: "Alice"} buf := &bytes.Buffer{} err := proto.BufferEncodeStringBytes(buf, u.Name) if err != nil { panic(err) } encoded := buf.Bytes() fmt.Println(encoded) // Output: [10 5 65 108 105 99 101] }In this example, we define a simple User struct and encode its Name field using the Buffer.EncodeStringBytes method. We then retrieve the encoded byte array from the buffer and print it to the console for demonstration purposes.