我希望变量model
可以是Model1
或Model2
,具体取决于bytes
中编码的实际模型。如何合并两个模型Result
,其中只有一个是Ok()
?
let model1 = Model1::from_reader(&mut reader, &bytes);
let model2 = Model2::from_reader(&mut reader, &bytes);
let model = /* ??? */;
write_file(model).unwrap();
他们都实现MessageWrite
,这是我从这一点开始需要的唯一特征。以下是write_file()
fn write_file<M: MessageWrite>(msg: M) -> io::Result<()>
我正在使用快速protobuf箱子模型。 from_reader
原型:
impl<'a> MessageRead<'a> for Model1<'a> {
fn from_reader(r: &mut BytesReader, bytes: &'a [u8]) -> Result<Self> {
// ...
}
}
MessageWrite
特质。请注意,它具有Sized
绑定。
pub trait MessageWrite: Sized {
// ...
}
答案 0 :(得分:4)
您可以使用模式匹配。见这个例子:
trait MessageWrite: Sized {}
struct Foo;
struct Bar;
impl MessageWrite for Foo {}
impl MessageWrite for Bar {}
fn main() {
let f: Result<Foo, ()> = Ok(Foo{});
let b: Result<Bar, ()> = Err(());
match (f, b) {
(Ok(f), _) => write_file(f),
(_, Ok(b)) => write_file(b),
_ => panic!(),
};
}
fn write_file<M: MessageWrite>(msg: M) -> std::io::Result<()> { Ok(()) }