1个稳定版本
1.0.0 | 2021年4月16日 |
---|
#17 在 #python-3
在 fstrings-rust 中使用
12KB
284 行代码(不包括注释)
::fstrings
-
注意,从1.58.0版本开始,这个crate已被弃用,因为在下面的代码中
let x = 42; println!("{x}");
被视为let x = 42; println_f!("{x}");
这里。这是一个先驱crate,现在已被 RFC 2795 吸收,该RFC成功推广了这个crate背后的思想!🏆
Rust中基本的fstring插值
插值的工作方式如下
-
如果(模板)字符串字面量包含一个命名参数(例如
{name}
) -
并且没有给格式化调用传递
name = value
参数, -
则自动添加
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