serialization - Can I implement the same trait multiple times in different ways for a single struct? -
i'd serialize struct in 2 different ways depending of situation i'm facing problem: current knowledge can serialize struct in 1 way.
here code #[derive(serialize)]
(auto derive)
#[derive(serialize, deserialize, partialeq, debug)] struct transactioncontent { sender_addr: vec<u8>, sender_pubkey: vec<u8>, receiver_addr: vec<u8>, amount: u32, timestamp: i64 }
i'm using bincode::serialize
serialize struct , make vec<u8>
, also want store struct in json file. when serializing json, i'd serialize in own way, returning base58 string vec<u8>
fields.
this own implementation:
impl serialize transactioncontent { fn serialize<s>(&self, serializer: s) -> result<s::ok, s::error> s: serializer { let mut state = serializer.serialize_struct("transactioncontent", 5)?; state.serialize_field("sender_addr", &self.sender_addr.to_base58())?; state.serialize_field("sender_pubkey", &self.sender_pubkey.to_base58())?; state.serialize_field("receiver_addr", &self.receiver_addr.to_base58())?; state.serialize_field("amount", &self.amount)?; state.serialize_field("timestamp", &self.timestamp)?; state.end() } }
i can't use above code simultaneously. if use auto derive, second impl
isn't possible. if use second one, bincode::serialize
function work not want (i want use vec<u8>
it)
is there way use both impl
@ same time? conditional impl
example?
no, cannot implement same trait multiple times in multiple ways single type.
as mentioned in comment, can create newtype wraps full data , implement required traits on that:
extern crate serde; extern crate serde_json; #[macro_use] extern crate serde_derive; use serde::{serialize, serializer}; use serde::ser::serializestruct; #[derive(debug, serialize)] struct real { data: vec<u8>, } struct asjson<'a>(&'a real); impl<'a> serialize asjson<'a> { fn serialize<s>(&self, serializer: s) -> result<s::ok, s::error> s: serializer, { let mut state = serializer.serialize_struct("thing", 1)?; state.serialize_field("data", b"this data")?; state.end() } } fn main() { let r = real { data: vec![1,2,3,4] }; println!("{:?}", serde_json::to_string(&r)); println!("{:?}", serde_json::to_string(&asjson(&r))); }
Comments
Post a Comment