This small project shows how to use prost-build to generate rust code from .proto files
First, you need to install protocol buffers: https://protobuf.dev/installation
Then run
$ cargo buildThe above command will compile src/user.proto using prost-build (see build.rs).
You can inspect the proto compilation result at /src/my_package.rs.
You can now run the small example (src/main.rs) that builds a User, encodes it, and then decodes it again:
$ cargo run
...
Struct User { id: 78, name: "Ale", email: Some("mrgonza78@gmail.com"), verified: true, interest: ["rust", "grpc"], links: {"linkedin": "www.linkedin.com/in/aagonzalez", "github": "github.com/mrgonza78"}, role: Member }
Encoded bytes: [8, 78, 18, 3, 65, 108, 101, 26, 19, 109, 114, 103, 111, 110, 122, 97, 55, 56, 64, 103, 109, 97, 105, 108, 46, 99, 111, 109, 32, 1, 42, 4, 114, 117, 115, 116, 42, 4, 103, 114, 112, 99, 50, 42, 10, 8, 108, 105, 110, 107, 101, 100, 105, 110, 18, 30, 119, 119, 119, 46, 108, 105, 110, 107, 101, 100, 105, 110, 46, 99, 111, 109, 47, 105, 110, 47, 97, 97, 103, 111, 110, 122, 97, 108, 101, 122, 50, 30, 10, 6, 103, 105, 116, 104, 117, 98, 18, 20, 103, 105, 116, 104, 117, 98, 46, 99, 111, 109, 47, 109, 114, 103, 111, 110, 122, 97, 55, 56, 56, 2]
Decoded: User { id: 78, name: "Ale", email: Some("mrgonza78@gmail.com"), verified: true, interest: ["rust", "grpc"], links: {"github": "github.com/mrgonza78", "linkedin": "www.linkedin.com/in/aagonzalez"}, role: Member }/protoc folder contains code generated/compiled from user.proto for other languages.
protoc is the Protocol Buffers compiler developed by Google. It takes .proto files—which define structured data schemas—and generates source code in various programming languages (such as C++, Java, Python, etc.) for serializing, deserializing, and manipulating the defined data structures
protoc rust code generation is still experimental.
If you feel like using protoc to generate the rust code, use
$ protoc src/user.proto --rust_out=protoc/rust \
--rust_opt=experimental-codegen=enabled \
--rust_opt=kernel=cppThis is how to compile .proto to other languages:
Ruby
$ protoc src/user.proto --ruby_out=protoc/rubyPython
$ protoc src/user.proto --python_out=protoc/pythonJava
$ protoc src/user.proto --java_out=protoc/javaC++
$ protoc src/user.proto --cpp_out=protoc/cppGo
$ protoc src/user.proto --go_out=protoc/go \
--go_opt=Msrc/user.proto=protos/