expression
Prost: encode and decode generated messages
Prost implements Message for generated messages. Encode to protobuf bytes, then decode using the same schema. Encoding does not guarantee application validity; validate decoded values separately. Run in the accompanying generated-bindings Cargo project. Expected stdout (not executed): [8, 7]; id=7 Common mistake: Treating protobuf as encrypted data or assuming every decoded ID is allowed.
Formal Syntax & Structure
rust syntaxrust
message.encode_to_vec(); T::decode(bytes.as_slice())Working Example
Example Snippetrust
#[tokio::main(flavor = "current_thread")]async fn main() { use bm_tonic_inventory::pb::GetItemRequest; use prost::Message; let original = GetItemRequest { id: 7 }; let bytes = original.encode_to_vec(); let decoded = GetItemRequest::decode(bytes.as_slice()).unwrap(); assert_eq!(original, decoded); println!("{:?}; id={}", bytes, decoded.id);}