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

How to displaydoc an Option? #39

Open
sffc opened this issue Dec 28, 2021 · 2 comments
Open

How to displaydoc an Option? #39

sffc opened this issue Dec 28, 2021 · 2 comments

Comments

@sffc
Copy link

sffc commented Dec 28, 2021

How can I write a displaydoc impl for the following struct?

#[displaydoc("{kind}: {str_context}")]
pub struct DataError {
    /// Broad category of the error.
    pub kind: DataErrorKind,

    /// Additional context, if available.
    pub str_context: Option<&'static str>,
}

This errors out with:

`std::option::Option<&str>` cannot be formatted with the default formatter

What I would like is to make an error that contains ": {str_context}" when Some and nothing when None.

Do I need to manually implement Display, or can I use displaydoc?

@yaahc
Copy link
Owner

yaahc commented Jan 4, 2022

Right now we don't have any support displaying options like this. We do have something similar on Path/PathBuf, where we will call display() transparently in the background, so I wouldn't be against adding some support for convenient formatting for Option.

I do have questions about the specific case you mentioned. It looks like you'd want to print "Some DataErrorKind Display: " with a trailing : and whitespace even when the str_context is None. Is this the correct behavior you'd like to see? Without knowing your specific usecase in detail my intuition is you'd want to show "Some DataErrorKind Display: some str_context" for the Some case and "SomeDataErrorKind Display" in the None case. I imagine we'd need something a bit more complicated to support the later case.

@sffc
Copy link
Author

sffc commented Jan 9, 2022

Without knowing your specific usecase in detail my intuition is you'd want to show "Some DataErrorKind Display: some str_context" for the Some case and "SomeDataErrorKind Display" in the None case.

Yes, that is what I meant. I would like to format with "{}: {}" when the context is Some and "{}" when the context is None. I was thinking a way to go about this would be to format the struct as a whole with "{}{}", where the second placeholder is ": {}" if Some or "" if None.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants