Implementation of fstring f strings

can we please bring fstrings to rust, it is so powerful and useful

#[macro_export]
macro_rules! f {
    ($fmt:expr $(,$arg:expr)*) => {
        format!($fmt $(,$crate::f::formatter($arg))*)
    };
}

pub mod f {
    pub fn formatter<T>(value: T) -> Formatter<T> {
        Formatter { value }
    }

    pub struct Formatter<T> {
        value: T,
    }

    impl<T> std::fmt::Display for Formatter<T>
    where
        T: std::fmt::Display,
    {
        fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
            self.value.fmt(f)
        }
    }
}

What is the purpose of this Formatter wrapper? And how is f!() different from format!()?

1 Like

Are you aware that Rust has supported captured identifiers in format strings since 1.58?

@bjorn3 @eggyal

Thank you for your feedback on my proposal to bring f-strings to Rust. I understand that Rust already supports captured identifiers in format strings since version 1.58, which is great news! This means that we can use variables directly in format strings without the need for any custom implementation like the f! macro.

Regarding the Formatter wrapper in the code I posted, I admit that it's not necessary in this case and could be removed. I was trying to provide a way to format values that do not implement the std::fmt::Display trait, but in retrospect, it's better to use Rust's Debug trait or to implement the Display trait for these types.

Thank you again for your feedback and insights. Rust's community is what makes it such a great language!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.