x
cargo new testpb
cd testpb/
cargo new snazzy --lib
在 snazzy/Cargo.toml 中添加:
x
[dependencies]
bytes = "1.2.1"
prost = "0.11.0"
[build-dependencies]
prost-build = "0.11.1"
prost-build 的文档在:https://docs.rs/prost-build/0.11.1/prost_build/。
创建 snazzy/build.rs:
x
fn main() {
let mut config = prost_build::Config::new();
config
.out_dir("src")
.compile_protos(&["src/items.proto"], &["."])
.unwrap();
}
创建 snazzy/src/items.proto:
x
syntax = "proto3";
package snazzy.items;
// A snazzy new shirt!
message Shirt {
enum Size {
SMALL = 0;
MEDIUM = 1;
LARGE = 2;
}
string color = 1;
Size size = 2;
}
修改 snazzy/src/lib.rs:
x
use std::io::Cursor;
use prost::Message;
// Include the `items` module, which is generated from items.proto.
pub mod items {
include!("snazzy.items.rs");
}
pub fn create_large_shirt(color: String) -> items::Shirt {
let mut shirt = items::Shirt::default();
shirt.color = color;
shirt.set_size(items::shirt::Size::Large);
shirt
}
pub fn serialize_shirt(shirt: &items::Shirt) -> Vec<u8> {
let mut buf = Vec::new();
buf.reserve(shirt.encoded_len());
// Unwrap is safe, since we have reserved sufficient capacity in the vector.
shirt.encode(&mut buf).unwrap();
buf
}
pub fn deserialize_shirt(buf: &Vec<u8>) -> Result<items::Shirt, prost::DecodeError> {
items::Shirt::decode(&mut Cursor::new(buf))
}
在 Cargo.toml 中添加:
xxxxxxxxxx
[dependencies]
snazzy = { path = "snazzy" }
修改 src/main.rs:
xxxxxxxxxx
fn main() {
let shirt = snazzy::create_large_shirt("White".to_string());
println!("{:?}", shirt);
let bytes: Vec<u8> = snazzy::serialize_shirt(&shirt);
println!("{:?}", bytes);
let shirt = snazzy::deserialize_shirt(&bytes);
println!("{:?}", shirt);
}
执行:
xxxxxxxxxx
cargo run
输出:
xxxxxxxxxx
Shirt { color: "White", size: Large }
[10, 5, 87, 104, 105, 116, 101, 16, 2]
Ok(Shirt { color: "White", size: Large })