#python #format #human #no-std #interpolation

no-std fstrings-rust

Python3 fstring interpolation in Rust

3 releases (stable)

1.0.1 Apr 16, 2021
0.2.2 Apr 16, 2021

#873 in Rust patterns

MIT license

112 lines


Repository Latest version Documentation License

Basic fstring interpolation in Rust

The interpolation works as follows:

  1. if the (template) string literal contains a named parameter (e.g. {name})

  2. and no name = value argument is fed to the formatting call,

  3. then an automatic name = name argument is added, so that the variable is effectively interpolated from the current scope.


extern crate fstrings;

fn main ()
    let name = "World";

    // Usage is simple: just append `_f` to the name of any formatting macro
    println_f!("Hello, {name}!");

        f!("Hello, {name}!"), // shorthand for String creation (Python-like)
        String::from("Hello, World!"),

    // ## Advanced cases:
        // It remains compatible with classic formatting parameters
            f!("{hi}, {name}!", hi = "Hello"),
            "Hello, World!",

        // You can override / shadow the named arguments
            f!("Hello, {name}!", name = "Earth"),
            "Hello, Earth!",

        // You can use field access (but no method calls!)
        let foo = Foo { name }; /* where */ struct Foo<T> { name: T }
            f!("Hello, {foo.name}!"),
            "Hello, World!",

        // This also works with tuple indexing.
        let ft_and_name = (42, name);
            f!("Hello, {ft_and_name.1}!"),
            "Hello, World!",

        // You can use fstrings to debug by appending a `=` after the
        // interpolated expression.
        let x = 0b_101010;
            f!("In this context {x=}"),
            "In this context x = 42",


~15K SLoC