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

no-std fstrings-rust

Python3 f字符串插值在Rust中

3个版本 (稳定)

1.0.1 2021年4月16日
0.2.2 2021年4月16日

#2475 in Rust模式

MIT 许可证

8KB
112 代码行

::fstrings

Repository Latest version Documentation License

Rust中的基本f字符串插值

插值工作如下

  1. 如果(模板)字符串字面量包含一个命名参数(例如 例如 {name}

  2. 并且没有给格式化调用传递 name = value 参数,

  3. 则自动添加一个 name = name 参数,以便变量可以从当前作用域中插值。

示例

#[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",
        );
    }
}

依赖关系

~1.5MB
~35K SLoC