Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
lucatrv opened this issue Jan 14, 2024 · 2 comments
Closed

Comments

@lucatrv
Copy link

lucatrv commented Jan 14, 2024

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
Copy link
Member

oli-obk commented Jan 15, 2024

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
Copy link
Author

lucatrv commented Jan 20, 2024

@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.

@oli-obk oli-obk closed this as completed Jan 21, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants