#template #fmt #format #control-flow #specifier

no-std fmtools

为 Rust 提供快速、最小化、功能丰富的扩展格式化语法!

3 个版本

0.1.2 2022 年 7 月 28 日
0.1.1 2022 年 7 月 9 日
0.1.0 2022 年 6 月 24 日

#98 in 模板引擎

Download history 181/week @ 2024-03-14 257/week @ 2024-03-21 352/week @ 2024-03-28 229/week @ 2024-04-04 194/week @ 2024-04-11 203/week @ 2024-04-18 209/week @ 2024-04-25 185/week @ 2024-05-02 222/week @ 2024-05-09 212/week @ 2024-05-16 212/week @ 2024-05-23 228/week @ 2024-05-30 194/week @ 2024-06-06 287/week @ 2024-06-13 244/week @ 2024-06-20 146/week @ 2024-06-27

914 每月下载量
用于 22 个 crates (6 直接)

MIT 许可证

26KB
428

格式化工具

MIT License crates.io docs.rs Build status

为 Rust 提供快速、最小化、功能丰富的扩展格式化语法!

功能包括

  • 格式化括号内的任意表达式
  • 在编译时生成优化过的 Rust 代码
  • 支持 rust-analyzer 自动完成、重构等功能!
  • 支持 Rust 的标准格式化说明符
  • 单个包,无 proc-macro,no_std 兼容,无额外依赖
  • 控制流允许条件性和重复的格式化
  • 按值或按引用捕获变量
  • 逃生舱口以注入自定义格式化代码

在您的 Cargo.toml 中添加

[dependencies]
fmtools = "0.1"

示例

基本用法

fn basic_usage() -> String {
	let name = "World";

	fmtools::format!("Hello "{name}"!")
}

assert_eq!(basic_usage(), "Hello World!");

值参数可以是任意表达式。它们内联在格式化括号中,并位于字符串字面量外部。

格式化说明符

fn formatting_specifiers() -> String {
	let value = 42;

	fmtools::format!("hex("{value}") = "{value:#x})
}

assert_eq!(formatting_specifiers(), "hex(42) = 0x2a");

说明符的规则与 Rust 标准库 完全相同。

引入变量绑定

fn let_bindings() -> String {
	let base = 52;

	fmtools::format! {
		let value = base - 10;
		"value = "{value}
	}
}

assert_eq!(let_bindings(), "value = 42");

引入新的变量绑定来保存格式化中使用的临时值。

控制流

fn control_flow1() -> String {
	let power = 0.5;

	fmtools::format! {
		"At "
		if power >= 1.0 { "full" }
		else { {power * 100.0:.0}"%" }
		" power"
	}
}

assert_eq!(control_flow1(), "At 50% power");
fn control_flow2() -> String {
	let value = Some(42);

	fmtools::format! {
		"The answer is "
		match value {
			Some(answer) => "Some("{answer}")",
			None => "None",
		}
	}
}

assert_eq!(control_flow2(), "The answer is Some(42)");
fn control_flow3() -> String {
	let values = [1, 2, 3, 4, 5];

	fmtools::format! {
		for &val in &values {
			let result = val * 5;
			"* "{val}" x 5 = "{result}"\n"
		}
	}
}

assert_eq!(control_flow3(), "\
	* 1 x 5 = 5\n\
	* 2 x 5 = 10\n\
	* 3 x 5 = 15\n\
	* 4 x 5 = 20\n\
	* 5 x 5 = 25\n");

控制流真正展示了扩展格式化语法的附加价值。

按值捕获

fn capture_by_value() -> String {
	fn inner() -> impl std::fmt::Display {
		let a = 42;
		fmtools::fmt!(move "a = "{a})
	}
	fmtools::format!("{"{inner()}"}")
}

assert_eq!(capture_by_value(), "{a = 42}");

可显示对象可以使用 move 拥有捕获的变量,并可以从函数中返回。

逃生舱口

fn escape_hatch() -> String {
	fmtools::format! {
		"Now entering ["
		|f| f.write_str("escape hatch")?;
		"]"
	}
}

assert_eq!(escape_hatch(), "Now entering [escape hatch]");

闭包语法提供逃生舱口以注入代码(如果需要)。参数的类型是 &mut Formatter

许可证

MIT 许可证 下授权,请参阅 license.txt

贡献

除非您明确声明,否则您有意提交的任何贡献,均应按上述方式授权,无需任何附加条款或条件。

依赖关系