12个版本

0.2.4-rc22021年4月16日
0.2.3 2020年4月22日
0.2.2 2019年11月3日
0.1.4 2019年8月4日
0.0.1 2019年7月27日

#16 in #python-3

Download history 471/week @ 2024-03-13 360/week @ 2024-03-20 338/week @ 2024-03-27 389/week @ 2024-04-03 387/week @ 2024-04-10 455/week @ 2024-04-17 397/week @ 2024-04-24 394/week @ 2024-05-01 497/week @ 2024-05-08 583/week @ 2024-05-15 664/week @ 2024-05-22 654/week @ 2024-05-29 402/week @ 2024-06-05 260/week @ 2024-06-12 382/week @ 2024-06-19 262/week @ 2024-06-26

1,465 下载/每月
14 个crate中使用 (via fstrings)

MIT 许可证

12KB
284 代码行

::fstrings

Repository Latest version Documentation MSRV License

  • 注意,此crate自1.58.0版本以来已被弃用,其中let x = 42; println!("{x}");在此处作为let x = 42; println_f!("{x}");执行。

    当然是一个先驱crate,现在已被RFC 2795所吸收,该RFC成功地推广了此crate背后的想法!🏆

Rust中基本的fstring插值

插值的工作方式如下

  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
~34K SLoC