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

Consider adding fmt::fmt_fn or fmt::from_fn to the standard library #102386

Closed
EFanZh opened this issue Sep 28, 2022 · 2 comments
Closed

Consider adding fmt::fmt_fn or fmt::from_fn to the standard library #102386

EFanZh opened this issue Sep 28, 2022 · 2 comments
Labels
C-feature-request Category: A feature request, i.e: not implemented / a PR.

Comments

@EFanZh
Copy link
Contributor

EFanZh commented Sep 28, 2022

Similar to iter::from_fn and future::poll_fn, I find it useful to have a fmt::fmt_fn or fmt::from_fn function that converts a function into a value that implements Debug and Display:

use std::fmt::{self, Debug, Display, Formatter};

pub struct FmtFn<F>(F)
where
    F: ?Sized;

impl<F> Display for FmtFn<F>
where
    F: Fn(&mut Formatter) -> fmt::Result + ?Sized,
{
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        (self.0)(f)
    }
}

impl<F> Debug for FmtFn<F>
where
    F: Fn(&mut Formatter) -> fmt::Result + ?Sized,
{
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        (self.0)(f)
    }
}

pub fn fmt_fn<F>(f: F) -> FmtFn<F>
where
    F: Fn(&mut Formatter) -> fmt::Result,
{
    FmtFn(f)
}

fn main() {
    assert_eq!(format!("{}", fmt_fn(|f| f.write_str("abc"))), "abc");
    assert_eq!(format!("{:?}", fmt_fn(|f| f.write_str("def"))), "def");

    let dst_fmt_fn: &FmtFn<dyn Fn(&mut Formatter) -> fmt::Result> = &fmt_fn(|f| f.write_str("ghi"));

    assert_eq!(format!("{}", dst_fmt_fn), "ghi");
}

Or maybe we can have two different functions: display_fn and debug_fn, where display_fn returns a value that implements Display, and debug_fn returns a value that implements Debug.

@EFanZh EFanZh changed the title Consider adding fmt::fmt_fn or fmt::from_fn to the standard library. Consider adding fmt::fmt_fn or fmt::from_fn to the standard library Sep 29, 2022
@Rageking8
Copy link
Contributor

@rustbot label +C-feature-request

@rustbot rustbot added the C-feature-request Category: A feature request, i.e: not implemented / a PR. label Sep 29, 2022
@EFanZh
Copy link
Contributor Author

EFanZh commented Jan 11, 2025

Superseded by #117729.

@EFanZh EFanZh closed this as completed Jan 11, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
C-feature-request Category: A feature request, i.e: not implemented / a PR.
Projects
None yet
Development

No branches or pull requests

3 participants