Rust protobuf serialization

I'm trying to serialize the protobuf message as bytes and send it over http as body. I tried the following but it doesn't work.

The proto file:

syntax = "proto3";
package user;
message user_data{
	string id = 1;
	string nick = 2;
	double credit = 3;
}

The build script (build.rs):

tonic_build::configure()
        .build_server(true)
        .build_client(true)
        .format(false)
        .compile(
            &[
                "src/proto/user/user.proto",
            ],
            &["src/proto/user"],
        )
        .expect("Error generating protobuf");

proto.rs file:

pub mod user_data{
    tonic::include_proto!("user");
}

The main.rs file:

mod proto;
use crate::proto::user_data::UserData;
use protobuf::Message;

fn main() {
    let tt = UserData{
        id: "1234".into(),
        nick: "test".into(),
        credit: 23.23,
    };
    let msg = tt.write_to_bytes().unwrap();
    let serialized = Message::parse_from_bytes(&msg).unwrap();
    println!("serialized: {:?}\noriginal: {:?}", serialized, tt)
}

The error I'm getting:
no method named write_to_bytes found for struct UserData in the current scope
--> src/main.rs:7:18
|
7 | let msg = tt.write_to_bytes().unwrap();
| ^^^^^^^^^^^^^^ method not found in UserData

I guess I'm doing something wrong, any advice how to serialize it to bytes ?

Can you post the Rust code generated by tonic::include_proto!. It should be available as an .rs file somewhere in your target/ directory.

Also, please put errors in code blocks too.

Looks like you're trying to use the protobuf::Message trait, however tonic uses prost for generating code from proto files, and prost has its own prost::Message trait.

2 Likes

thanks it works now, the new code:

mod proto;
use crate::proto::user_data::UserData;
use prost::Message;

fn main() {
    let tt = UserData{
        id: "1234".into(),
        nick: "test".into(),
        credit: 23.23,
    };
    let mut buf = vec![];
    tt.encode(&mut buf).unwrap();

    let decoded: UserData = Message::decode(&buf[..]).unwrap();
    println!("serialized: {:?}\noriginal: {:?}", buf, decoded)
}