Feature request: Add a way to capture a formatter that can be passed to format helper functions #74870
Labels
C-feature-request
Category: A feature request, i.e: not implemented / a PR.
T-libs-api
Relevant to the library API team, which will review and decide on the PR/issue.
Motivation
The Display trait allows lazy formatting of data. The formatter is passed in and used by the implemented
fmt
function for the struct. Often however applications and libraries want to expose helper functions to compose the display parts of a complex struct.There are several ways to solve that:
The motivation however here is that not only the Display::fmt function can be called by the user, but also the helper functions to format just parts of the struct (in our use-case different statistics).
The signature of the helper functions is the same as of fmt in the Display trait:
But it is not possible to construct a formatter manually.
The only way to be able to call the helper function is to use:
The format crate or a helper Fmt() struct, which can capture the formatter passed in.
Proposed resolution
To solve that I am arguing that either a macro or a Fmt helper trait should be available in core rust so that there exists no function that you just can't call as a user (without an extra crate or helper trait).
The usage looks for example like this:
The implementation of Fmt is as follows:
(from: https://users.rust-lang.org/t/reusing-an-fmt-formatter/8531/3)
Discussion
I am not sure if
Fmt
is the right name as it feels a little bit weird.Alternative proposals are like the
format
crate does it using a macro:Or what would be great if via some compiler magic a closure could directly work:
From a user experience perspective the last version feels ideal, but I am not sure how difficult it would be to implement that.
Next steps
Related issues
Change scope
The scope is a small addition and hence seemed to not need a RFC per the guide lines.
If this has a chance of going in, I am happy to provide a PR.
The text was updated successfully, but these errors were encountered: