serde-rs / serde

Serialization framework for Rust
https://serde.rs/
Apache License 2.0
9.06k stars 767 forks source link

Feature Request: please add support for `Result<T, E>` to the Serde data model #2675

Closed lucatrv closed 8 months ago

lucatrv commented 8 months ago

Currently the Serde data model supports Option<T>, which can be used when a value maybe present or not. However often when deserializing data fields which should be of a certain type, we need to define a fallback type to store invalid values. Consider for instance an Excel column which should contain f64 values, but may sometimes contain an invalid string. This very common occurrence can be dealt with by using Result<f64, String>. All values which correctly deserialize to f64 would be returned as Ok(value), while all invalid strings would be returned as Err(string). The default value should be Err(Default:default()), returned for empty fields when #[serde(default)] is specified. Finally there should be a way to specify when using to_string_lossy instead of to_string. I am not sure if this is feasible but for instance to_string_lossy could be applied for Result<T, Cow<'_, str>> types. Of course also other use cases can be envisioned for a Result<T, E> type.

When #[serde(default)] is specified, for empty fields the following function should be applied:

fn default_result<T, E>() -> Result<T, E>
where
    E: Default,
{
    Err(Default::default())
}
oli-obk commented 8 months ago

This is something you can implement support for in a separate crate to be used with https://serde.rs/field-attrs.html#deserialize_with

Serde normally doesn't support something so specific to self-describing serialization formats, and I don't think this case is common enough for there to be support within serde.

lucatrv commented 8 months ago

@oli-obk, thanks for your answer, IMHO dealing with invalid data is rather common indeed. I thought that one of the reasons to include option in the Serde data model was to manage fields which may bring either valid or invalid values. In case of option, invalid values are discarded, such as with csv::invalid_option. In case of result instead, invalid values would be returned through the fallback type, see for instance csv::invalid_result. I understand however if you think that this feature should be managed specifically and separately within each crate, in this case please feel free to close this issue.