我正在尝试进行结构体序列化,其中字节最终将通过管道发送,重建后并对其调用方法。
我创建了一个适当的 trait 供这些结构体实现,并使用 serde 和 serde-cbor 进行序列化:
extern crate serde_cbor;
#[macro_use]
extern crate serde_derive;
extern crate serde;
use serde_cbor::ser::*;
use serde_cbor::de::*;
trait Contract {
fn do_something(&self);
}
#[derive(Debug, Serialize, Deserialize)]
struct Foo {
x: u32,
y: u32,
}
#[derive(Debug, Serialize, Deserialize)]
struct Bar {
data: Vec<Foo>,
}
#[derive(Debug, Serialize, Deserialize)]
struct Baz {
data: Vec<Foo>,
tag: String,
}
impl Contract for Bar {
fn do_something(&self) {
println!("I'm a Bar and this is my data {:?}", self.data);
}
}
impl Contract for Baz {
fn do_something(&self) {
println!("I'm Baz {} and this is my data {:?}", self.tag, self.data);
}
}
fn main() {
let data = Bar { data: vec![Foo { x: 1, y: 2 }, Foo { x: 3, y: 4 }, Foo { x: 7, y: 8 }] };
data.do_something();
let value = to_vec(&data).unwrap();
let res: Result<Contract, _> = from_reader(&value[..]);
let res = res.unwrap();
println!("{:?}", res);
res.do_something();
}
当我尝试使用trait作为类型来重构字节(假设我不知道正在发送哪个基础对象),编译器会抱怨该trait没有实现Sized trait:
当我尝试使用trait作为类型来重构字节(假设我不知道正在发送哪个基础对象),编译器会抱怨该trait没有实现Sized trait:
error[E0277]: the trait bound `Contract: std::marker::Sized` is not satisfied
--> src/main.rs:52:15
|
52 | let res: Result<Contract, _> = from_reader(&value[..]);
| ^^^^^^^^^^^^^^^^^^^ the trait `std::marker::Sized` is not implemented for `Contract`
|
= note: `Contract` does not have a constant size known at compile-time
= note: required by `std::result::Result`
我猜这是因为编译器不知道结构体应该有多大并且不知道如何对齐字节。如果我更改反序列化对象的那一行来指定实际的结构体类型,它就可以工作:let res: Result<Bar, _> = from_reader(&value[..]);
有没有更好的模式来实现这种序列化+多态行为?