How best to implement a custom Option type #595
-
Hi, I have a CSV-like data format that has optional fields that sometimes are blank and sometimes have a fixed string in them ("--"). I've been trying to implement a custom type that implements DeserializeAs but I'm not really sure the best way to do it. I'd kinda like to "peek" into the field and check if it's empty or with that fixed string and then pass the deserializer to the type that's contained but I can't really figure out a good way to do that. Thanks for your help. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Peeking is impossible with serde, because any In your case you can deserialize a |
Beta Was this translation helpful? Give feedback.
Peeking is impossible with serde, because any
deserialize_*
method onDeserializer
consumes theDeserializer
. What serde does to simulate peeking is deserialize into aValue
-like type, which can hold any data, and then deserialize from theValue
, potentially multiple times. That strategy has some downsides though.In your case you can deserialize a
String
orOption<String>
and inspect that. You can turn theString
into aDeserializer
for example withStringDeserializer
.The
StringDeserializer
is relativly strict and only providesStrings
, whereas the originalDeserializer
might be more lenient and offer integers or booleans (I don't recall what csv can do exactly). If you need that you mu…