How to use protobuf?

I was trying to use this protobuf crate to generate rust files using this build.rs:

protobuf_codegen::Codegen::new()
   .protoc()
   .cargo_out_dir("generated_with_native")
   .input("src/protos/capabilities.proto")
   .include("src/protos")
   .run_from_script();

I tried including generated rs code via this:

pub mod proto {
   include!(concat!(env!("OUT_DIR"), "/generated_with_native/capabilities.rs"));
}

The problem is that I have got a lot of issues like this:

error: an inner attribute is not permitted in this context
 --> /home/dimanne/devel/scripts/observability/target/debug/build/input-20af024046742d76/out/generated_with_native/capabilities.rs:6:1
  |
6 | #![allow(unknown_lints)]
  | ^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: inner attributes, like `#![no_std]`, annotate the item enclosing them, and are usually found at the beginning of source files
  = note: outer attributes, like `#[test]`, annotate the item following them

I think the crux of the issue is that codegen inserted a bunch of attributes, and then I included them in a another file, and rust is not happy that internal attributes are pulled via include in another file.

What is the correct way to use protobuf in rust?

I only use started playing with protobufs. My build.rs looks like this:

fn main() {
    protobuf_codegen::Codegen::new()
        .cargo_out_dir("protos")
        .include("src")
        .input("src/protos/example.proto")
        .run_from_script();

}

I include the generated code like so:

include!(concat!(env!("OUT_DIR"), "/protos/mod.rs"));

Hmm...looks like yours.

I don't get any #! in the generated code. Everything works fine.

2 Likes

Interesting... can you please share first 20-30 lines of your generated .rs file?

Never mind, I had to include mod.rs (not /capabilities.rs)
Now everything works.
Thanks.

Oops, sorry. I did not notice that difference in our snippets.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.