我如何反序列化为特征,而不是具体类型?

Das*_*h83 10 serialization rust cbor serde

我正在尝试进行结构序列化,其中字节最终将被发送到管道,重建并在它们上调用方法.

我创建了一个特征,这些结构将适当地实现,我使用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();
}
Run Code Online (Sandbox Code Playgroud)

当我尝试使用特征作为类型重建字节时(假设我不知道发送了哪个底层对象),编译器会抱怨特征没有实现Sized特征:

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`
Run Code Online (Sandbox Code Playgroud)

我想它是有道理的,因为编译器不知道结构应该有多大,也不知道如何为它排列字节.如果我更改反序列化对象的行以指定实际的结构类型,它的工作原理如下:

let res: Result<Bar, _> = from_reader(&value[..]);
Run Code Online (Sandbox Code Playgroud)

是否有更好的模式来实现此序列化+多态行为?

oli*_*obk 8

看起来你陷入了我从C++搬到Rust时陷入的陷阱.试图使用多态来建模一组固定的变体.Rust的枚举(类似于Haskell的枚举,相当于Ada的变体记录类型)与其他语言中的经典枚举不同,因为枚举变体可以有自己的字段.

我建议你改变你的代码

#[derive(Debug, Serialize, Deserialize)]
enum Contract {
    Bar { data: Vec<Foo> },
    Baz { data: Vec<Foo>, tag: String },
}

#[derive(Debug, Serialize, Deserialize)]
struct Foo {
    x: u32,
    y: u32,
}

impl Contract {
    fn do_something(&self) {
        match *self {
            Contract::Bar { ref data } => println!("I'm a Bar and this is my data {:?}", data),
            Contract::Baz { ref data, ref tag } => {
                println!("I'm Baz {} and this is my data {:?}", tag, data)
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


She*_*ter 6

您可以使用typetag来解决问题。添加#[typetag::serde](或::deserialize,如此处所示)到特征和每个实现:

use serde::Deserialize;

#[typetag::deserialize(tag = "driver")]
trait Contract {
    fn do_something(&self);
}

#[derive(Debug, Deserialize, PartialEq)]
struct File {
    path: String,
}

#[typetag::deserialize(name = "file")]
impl Contract for File {
    fn do_something(&self) {
        eprintln!("I'm a File {}", self.path);
    }
}

#[derive(Debug, Deserialize, PartialEq)]
struct Http {
    port: u16,
    endpoint: String,
}

#[typetag::deserialize(name = "http")]
impl Contract for Http {
    fn do_something(&self) {
        eprintln!("I'm an Http {}:{}", self.endpoint, self.port);
    }
}

fn main() {
    let f = r#"
{
  "driver": "file",
  "path": "/var/log/foo"
}
"#;

    let h = r#"
{
  "driver": "http",
  "port": 8080,
  "endpoint": "/api/bar"
}
"#;

    let f: Box<dyn Contract> = serde_json::from_str(f).unwrap();
    f.do_something();

    let h: Box<dyn Contract> = serde_json::from_str(h).unwrap();
    h.do_something();
}
Run Code Online (Sandbox Code Playgroud)
[dependencies]
serde_json = "1.0.57"
serde = { version = "1.0.114", features = ["derive"] }
typetag = "0.1.5"
Run Code Online (Sandbox Code Playgroud)

也可以看看: