12 releases

0.2.4-rc2 Apr 16, 2021
0.2.3 Apr 22, 2020
0.2.2 Nov 3, 2019
0.1.4 Aug 4, 2019
0.0.1 Jul 27, 2019

#2110 in Rust patterns

Download history 444/week @ 2023-11-27 422/week @ 2023-12-04 567/week @ 2023-12-11 692/week @ 2023-12-18 696/week @ 2023-12-25 412/week @ 2024-01-01 598/week @ 2024-01-08 597/week @ 2024-01-15 581/week @ 2024-01-22 632/week @ 2024-01-29 376/week @ 2024-02-05 673/week @ 2024-02-12 1263/week @ 2024-02-19 487/week @ 2024-02-26 582/week @ 2024-03-04 169/week @ 2024-03-11

2,573 downloads per month
Used in 13 crates (9 directly)

MIT license

10KB
141 lines

::fstrings

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.

Example

#[macro_use]
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}!");

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

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

        // You can override / shadow the named arguments
        assert_eq!(
            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 }
        assert_eq!(
            f!("Hello, {foo.name}!"),
            "Hello, World!",
        );

        // This also works with tuple indexing.
        let ft_and_name = (42, name);
        assert_eq!(
            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;
        assert_eq!(
            f!("In this context {x=}"),
            "In this context x = 42",
        );
    }
}

Dependencies

~1.5MB
~32K SLoC