#2.10. fmt:格式化 trait
本页内容
- 2.10.1. 分派
- 2.10.2. Formatter
- 2.10.3. Display
- 2.10.4. Debug
- Display vs Debug
- 用户定义 / derive
- 美化输出,{:#?}
- 2.10.5. 整数说明符
- 2.10.6. 浮点输出
- 2.10.7. 完整的 f-string 格式说明符语法
- 动态说明符
- 2.10.8. align / fill / width / precision
- 2.10.9. 模块对应
- 2.10.10. #[derive(Debug)]
- 2.10.11. REPL / print / 自动输出
- 2.10.12. FmtError
- 2.10.13. 与其他语言的比较
- 2.10.14. 派生策略小结
- #[display("..")]
- 2.10.15. Arguments:稍后格式化的 f-string
core::fmt 模块定义了一组把值转换为人类可读字符串的 trait。f-string 中的每个格式说明符(f"{x}"、f"{x:?}"、f"{n:08b}" 等)都分派到本章的 trait。
f-string 的含义由 refs-lang 1.7.4 f-string 格式说明符中的词法分解与本章的 trait 分派共同决定。
#2.10.1. 分派
f-string 的插值位 {expr[:spec]} 在说明符的 type 为 ? 时调用 Debug::fmt,否则调用 Display::fmt。说明符的其余部分(fill / align / sign / # / 0 / width / precision 以及 b o x X e E f)由 Formatter 携带。
- 数字(所有整数、浮点类型、
int、float)直接把说明符应用到自己的输出上(2.10.5、2.10.6)。 - 其他值的
Display::fmt能看到说明符中的精度、符号、#、分组和类型字母,但看不到宽度(f.width()为none):包装数字的类型把这些交给内部的数字,所以Complex的f"{z:.2}"是1.23+2.50i,f"{z:.1e}"是1.2e0+2.5e0i,而f.pad(s)按精度截断文本。因此,这样的值在静态说明符和动态说明符中都接受数字的类型字母(e、x、%等)。随后 Formatter 对值写出的内容应用 fill / align / width。str和Debug::fmt({x:.3?})看不到说明符;它们的文本按精度截断。
d / s 是默认表示法的别名;g 是数字的通用格式(1.23e+03)。各符号和标志的含义定义在 refs-lang 1.7.3 中。f-string 不为每个插值位构建中间字符串,而是把每个插值位依次写入同一个 Formatter 的缓冲区。
#2.10.2. Formatter
struct Formatter { .. } // output buffer + current spec
enum Alignment { Left, Right, Center, Equal }
enum Sign { Plus, Minus, Space }
impl Formatter {
fn new() -> Formatter;
fn with_capacity(n: usize) -> Formatter;
fn with_spec(spec: FormatSpec) -> Formatter;
fn from_sink(sink: fn(str) -> bool) -> Formatter; // hands its text to sink in chunks
fn finish(self) -> str; // text written so far
fn flush(ref self) throws (FmtError); // hands what a from_sink formatter holds to its sink
fn write_str(ref self, s: str) throws (FmtError);
fn write_char(ref self, c: char) throws (FmtError);
fn write_fmt(ref self, args: Arguments) throws (FmtError); // an f-string, piece by piece (2.10.15)
fn pad(ref self, s: str) throws (FmtError); // applies fill / align / width / precision
fn pad_integral(ref self, is_nonnegative: bool, prefix: str, digits: str) throws (FmtError);
// sign + # prefix + 0 / fill padding
fn fill(self) -> char;
fn align(self) -> Alignment | none; // none: default (right for numbers, left otherwise)
fn sign(self) -> Sign | none;
fn alternate(self) -> bool; // #
fn zero_pad(self) -> bool; // 0
fn width(self) -> usize | none;
fn precision(self) -> usize | none; // at most 500
fn ty(self) -> char; // '\0' for none or `s d`
}
由 from_sink 创建的格式化器最多保存大约一个块(4 KiB)的文本:一次 write_str 或 pad 之后若已保存这么多,它就把文本交给 sink 并开始新的块,flush 则交出剩余部分。sink 返回 false 时写入以 FmtError 失败,于是向它写入的 Display 随之停止。io::Write::write_display(2.23.3)建立在它之上。
FormatSpec 是解析后的说明符值。静态说明符在编译时解析;动态说明符(含有 {..} / ${..} 的说明符)在运行时解析一次。
struct FormatSpec {
fill: char; align: Alignment | none; sign: Sign | none; alt: bool; zero: bool;
width: usize | none; precision: usize | none; ty: char;
}
impl FormatSpec {
fn new() -> FormatSpec; // empty spec
fn parse(text: str) throws (ValueError) -> FormatSpec;
fn fill(self) -> char; // ' ' when none is given
fn align(self) -> Alignment | none;
fn sign(self) -> Sign | none;
fn alternate(self) -> bool; // #
fn zero_pad(self) -> bool; // 0
fn width(self) -> usize | none;
fn precision(self) -> usize | none;
fn ty(self) -> char; // '\0' for none or `s d`
}
parse 抛出 ValueError,指出哪里有误。字段是私有的:通过 getter 读取说明符,Formatter 也有同名的 getter。Formatter::with_spec 把精度上限定为 500:更大的精度按 500 处理。这样,新增字段永远不会破坏使用说明符的代码。
#2.10.3. Display
#[lang("display_trait")]
trait Display {
fn fmt(self, ref f: Formatter) throws (FmtError);
}
这是 f"{x}" 的默认分派。原始数字类型的 fmt 在一次运行时调用中应用说明符并写出。
impl Display for str {
fn fmt(self, ref f: Formatter) throws (FmtError) { try f.pad(self) }
}
struct Point { x: f64; y: f64; }
impl Display for Point {
fn fmt(self, ref f: Formatter) throws (FmtError) {
try f.write_str("(");
try Display::fmt(self.x, ref f);
try f.write_str(", ");
try Display::fmt(self.y, ref f);
try f.write_str(")");
}
}
f"{Point { x: 1.5, y: 2.5 }}"; //→ "(1.5, 2.5)"
f"{Point { x: 1.5, y: 2.5 }:>12}"; //→ " (1.5, 2.5)" (f.width() inside Point::fmt is none)
- 调用处必须写
ref(Display::fmt(x, ref f))。对于同时实现Display和Debug的类型,x.fmt(f)这种形式有歧义,所以调用写成路径形式。 Display不能派生。由类型的设计者决定其表示形式。
#2.10.4. Debug
#[lang("debug_trait")]
trait Debug {
fn fmt(self, ref f: Formatter) throws (FmtError);
}
impl Debug for str { .. } // a valid nabi string literal
impl Debug for char { .. } // a valid nabi character literal
这是 f"{x:?}" 的分派;它的目标是能读回的表示形式。浮点值会表明自己是浮点数:整数值加上 .0({1.0:?} 是 1.0,{[1.0, 2.5]:?} 是 [1.0, 2.5])。str / char 的 Debug 输出是 Nabi 字面量。引号、\\、\n / \r / \t 等会被转义;其他控制字符和双向文本字符(U+202A..U+202E、U+2066..U+2069 等)写成 \u{..}。
#Display vs Debug
两个 trait 的用途不同,汇总如下表。
| 方面 | Display | Debug |
|---|---|---|
| 受众 | 最终用户 | 开发者 |
| 准确性 | 可读性优先 | 不丢失信息(目标是能往返) |
| 引号 | 字符串原样输出(无引号) | 字符串包在 "..." 中(带转义) |
| 容器 | 通常不定义 | 所有集合类型自动具备 |
| derive | 不允许(手动实现) | 允许(#[derive(Debug)]) |
let s = "hello\nworld";
let d1 = f"{s}"; //→ hello
// world (Display: as is)
let d2 = f"{s:?}"; //→ "hello\nworld" (Debug: escaped)
#用户定义 / derive
#[derive(Debug)]
struct Point { x: f64; y: f64; }
let p = Point { x: 1.5, y: 2.5 };
let s = f"{p:?}"; //→ "Point { x: 1.5, y: 2.5 }"
Debug 可以通过组合每个字段的 Debug 输出自动派生。
#美化输出,{:#?}
# 会传给值的 Debug(f.alternate())。此时派生的 Debug、集合类型、数组和元组每行写一个条目,缩进四个空格,每个条目以 , 结尾:
f"{p:#?}"; //→ Point {
// x: 1.5,
// y: 2.5,
// }
f"{[1, 2]:#?}"; //→ [
// 1,
// 2,
// ]
空集合仍是 [] / {}。
#2.10.5. 整数说明符
type | 整数 |
|---|---|
(无)、d、s | 十进制 |
g | 通用格式({1234567:g} → 1.23457e+06) |
f | 定点({5:.2f} → 5.00) |
b o x X | 二进制 / 八进制 / 十六进制(加 # 时带 0b / 0o / 0x) |
e E | 指数表示法 |
对浮点值使用 b o x X 是编译错误(静态说明符)或 panic(动态说明符)。定宽负整数按该类型位宽的二进制补码输出({-1i8:x} 是 "ff")。int 按符号加绝对值的形式输出(int 值 -255 配 {n:x} 是 "-ff")。
let n: u32 = 0xCAFE;
f"{n:b}"; //→ "1100101011111110"
f"{n:#x}"; //→ "0xcafe"
f"{n:X}"; //→ "CAFE"
f"{42:08b}"; //→ "00101010"
f"{42:e}"; //→ "4.2e1"
#2.10.6. 浮点输出
{}写出能读回同一个值的最短数字串,不使用指数表示法。1.0是1,0.1是0.1,NaN 是NaN,无穷大是inf/-inf。{:e}用指数表示法写出同样的数字(0.15是1.5e-1)。{:E}使用E。- 给出精度时,值舍入到相应的位数(
{x:.3e}、{x:.2})。 {:g}是通用格式(refs-lang 1.7.3):1234.5678的{x:.3g}是1.23e+03,{1e20:g}是1e+20。{:?}等同于{},但整数值带.0(1.0、-0.0);仅限不带精度时。- 提升后的
float(指数超出 f64 范围)即使用{}也以指数表示法写出(1.5e400)。
let x: f64 = 12345.678;
f"{x}"; //→ "12345.678"
f"{x:e}"; //→ "1.2345678e4"
f"{x:.3e}"; //→ "1.235e4"
f"{1.0}"; //→ "1"
f"{1.0:?}"; //→ "1.0"
f"{x:.3g}"; //→ "1.23e+04"
#2.10.7. 完整的 f-string 格式说明符语法
权威定义在 refs-lang 1.7.3 中;这里是摘要。
spec = [fill][align][sign][#][0][width][grouping][.precision][type]
grouping = "," | "_"
align = "<" | ">" | "^" | "="
sign = "+" | "-" | " "
type = "" | "s" | "d" | "g" | "f" | "?" | "b" | "o" | "x" | "X" | "e" | "E" | "%"
width = unsigned-int | hole
precision = unsigned-int | hole
hole = "{" expr "}" | "${" expr "}" // nested hole, no spec of its own
fill = any single char (default: space)
分组。 , 在十进制数整数部分每三位数字之间加逗号,_ 加下划线(在 b o x X 中每四位):f"{1234567:,}" 是 1,234,567,f"{x:_x}" 对十六进制数字分组。分组只适用于数字,, 只适用于十进制形式;其他情况都是错误。用 0 填充时不插入分隔符。
百分比。 % 以 f 形式写出数字乘以 100 的结果(未给出精度时为 6 位小数),再加一个 %:f"{0.1234:.1%}" 是 12.3%。
回显。 {expr=} 写出插值位的源代码文本直到并包括 =(保留空格),再写出值的 Debug 形式;带说明符时,{expr=:spec} 改用该说明符写出值(即 Python 的 f"{x=}"):f"{x=}" 是 x=5,f"{x = :.2}" 是 x = 5.00。
#动态说明符
let s1 = f"{x:.{prec}}"; //→ "3.1416" (dynamic precision)
let s2 = f"{x:>${width}.${prec}}"; //→ " 3.1416" (dynamic width + precision)
let s3 = f"{x:{full_spec}}"; //→ ... (entire spec dynamic)
说明符中的 $$ 是单个 $。正文中的 $ 是字面字符(f"cost: $100")。静态说明符在编译时检查;动态说明符展开后若无效,会在运行时 panic。词法分析器的切分遵循 refs-lang 1.7.3 中的“词法处理”。
#2.10.8. align / fill / width / precision
Formatter::pad 自动处理说明符中的 align、fill 和 width,所以用户实现只需产生内容。
未显式指定 align 时,数字(整数、浮点数)右对齐,其他所有类型左对齐。给出 < / > / ^(以及 fill)时,任何类型都按该对齐方式处理。?(Debug)同样接受 width / align。
let n: i32 = 42;
f"{n}"; //→ "42" (default)
f"{n:5}"; //→ " 42" (width 5, numbers right-aligned by default)
f"{n:<5}"; //→ "42 " (left)
f"{n:>5}"; //→ " 42" (right)
f"{n:^5}"; //→ " 42 " (center)
f"{n:0>5}"; //→ "00042" (fill 0)
f"{n:*^7}"; //→ "**42***" (fill *, center, width 7)
f"{n:=+5}"; //→ "+ 42" (= : pad between sign and digits, + : sign on positives)
f"{n:+=5}"; //→ "+++42" (fill '+', align '=')
f"{-42:=6}"; //→ "- 42"
f"{-42:06}"; //→ "-00042" (0 : pad with 0, = alignment)
f"{n:+}"; //→ "+42" (+ : sign on positives too)
f"{"ab":5}"; //→ "ab " (strings left-aligned by default)
precision 的应用方式相同。
let x: f64 = 3.141592653589793;
f"{x:.2}"; //→ "3.14" (2 digits after the point)
f"{x:.0}"; //→ "3"
f"{x:10.4}"; //→ " 3.1416" (width 10, precision 4, numbers right-aligned by default)
f"{x:<10.4}"; //→ "3.1416 " (left alignment requires explicit <)
字符串上的精度解释为截断到最大长度;整数上的精度被忽略。
let s = "hello world";
f"{s:.5}"; //→ "hello"
f"{n:.3}"; //→ "42"
#2.10.9. 模块对应
下表列出每种类型实现了哪些 trait。
| 类型 | Display | Debug |
|---|---|---|
整数、int、浮点数、float | ✓ | ✓ |
bool、char、str | ✓ | ✓ |
List<T>、Set<T> | ✗ | ✓(T: Debug) |
Dict<K, V> | ✗ | ✓(K, V: Debug) |
(A, B, ..) | ✗ | ✓(全部 Debug) |
T | none | ✗ | ✓(T: Debug) |
Result<T, E> | ✗ | ✓(T, E: Debug) |
Display 只存在于标量、字符串以及手动实现它的用户类型;容器没有 Display。Debug 几乎存在于所有类型,并由 derive 生成。
#2.10.10. #[derive(Debug)]
#[derive(Debug)]
struct User { id: u64; name: str; }
let u = User { id: 1, name: "Alice" };
let s = f"{u:?}"; //→ User { id: 1, name: "Alice" }
derive 的行为如下。结构体输出为 TypeName { field1: <field1:?>, field2: <field2:?>, ... },元组结构体输出为 TypeName(<f1:?>, <f2:?>, ...)。枚举输出为 VariantName 或 VariantName(...) / VariantName { ... }。derive 要求每个字段都(递归地)实现 Debug。
没有 #[derive(Display)]。决定表示形式是用户的责任。
#2.10.11. REPL / print / 自动输出
refs-lang 9.7 JIT 单元执行流程的 REPL 一节定义了以下行为。
>>> let x = 42;
>>> x
42
>>> 1 + 2
3
>>> "hello"
hello
>>> "hello"?
"hello"
REPL 自动打印最后一个表达式时使用 Display,没有则用 Debug;末尾的 ? 打印 Debug 形式,:type 打印类型。两者都没有的值(对末尾的 ? 而言是没有 Debug)只打印其类型名(refs-lang 9.7.7、2.12.4)。
直接调用 print、println、eprint 或 eprintln 时,可以传任意数量的值以及具名参数 sep: 和 end::
println("total:", n, xs); // total: 3 [1, 2, 3]
println(a, b, sep: ", ");
print("no newline", end: "");
println(); // a blank line
每个值都用 Display 写出;类型没有 Display 但有 Debug 的值用 Debug 写出(所以 List 打印为 [1, 2, 3]),与 REPL 相同。各值之间用 sep(默认 " ")连接,最后跟上 end(println / eprintln 默认 "\n",print / eprint 默认为空);sep 和 end 在各值之后求值,整段文本在一次调用中写出,所以不同线程的行永远不会交错。其他具名参数都是错误。f-string 仍然是格式化手段:插值位接受说明符,且从不回退到 Debug(2.10.4)。没有 print("{}", x) 这样的位置格式字符串形式。
作为值使用时(xs.for_each(println)),每个都是如下函数
pub fn println<T: Display>(v: T = ""); // likewise print / eprint / eprintln
dbg。 dbg(e) 向 stderr 写出 [file:line:col] <e's source text> = <e:?> 和换行,并返回 e 的值(即 Rust 的 dbg!):let y = dbg(x * 2) + 1;。作为值使用时它是 fn dbg<T: Debug>(value: T) -> T,只写出 Debug 形式。
RichDisplay 与 display。 能在笔记本中以文本以外的形式显示的值实现
pub trait RichDisplay {
/// MIME type to content: `image/svg+xml`, `text/html`, `text/markdown`,
/// `text/latex`, `application/json` as text; `image/png` and other
/// binary types base64-encoded; `text/plain` for other front ends.
fn mime_bundle(self) -> Dict<str, str>;
}
pub fn display<T: RichDisplay>(x: T);
在 nabi jupyter 笔记本中,值具有 RichDisplay 的单元会以 display_data 显示其 bundle,display(x) 则在单元中途显示一个(refs-lang 9.8.2)。在其他地方(程序、终端 REPL),display(x) 把 bundle 的 text/plain 和换行写到 stdout,没有 text/plain 时什么也不写;终端 REPL 按上文显示单元的值。绘图库的图形提供 image/svg+xml,表格提供 text/html。
to_str。 每个 Display 类型都有 x.to_str() -> str,即它的 Display 文本(Python 的 str(x)),由 core::fmt 的通用实现 impl<T: Display> ToStr for T 提供。类型自己的 to_str 优先。
#2.10.12. FmtError
struct FmtError;
impl FmtError {
fn message(self) -> str; // "an error occurred when formatting"
}
// + Display, Debug, Error, PartialEq, Eq, Clone
向流写入失败时的错误。写入内存(f-string、Formatter::new 等)时不会发生;from_sink 格式化器在其 sink 拒绝一个块时产生它。所有 fmt 方法都是 throws (FmtError),所以调用要用 try 标记以便传播。
#2.10.13. 与其他语言的比较
下表展示 Nabi 的 fmt 设计相对于 Rust 和 Python 的位置。
| 方面 | Rust Display/Debug | Python __str__/__repr__ | Nabi |
|---|---|---|---|
| 面向人 / 调试的区分 | ✓ 独立的 trait | ✓ 独立的方法 | ✓ 独立的 trait |
| Debug derive | #[derive(Debug)] | 自动默认 | #[derive(Debug)] |
| Display derive | 不允许 | 不允许(手动) | 不允许 |
| 进制 / 指数 | 6 个 trait | 格式说明符 | 携带说明符的 Formatter |
| 动态说明符 | 位置参数({0:.*}) | f-string {:.{prec}} | ${...} 表达式($ 符号) |
| 说明符语法 | 类似 Python | PEP 3101 | 类似 Python + ${...} |
Nabi 最有特色的选择是用 ${...} 在视觉上区分动态说明符的插入,避免了 Python {:.{prec}} 中嵌套花括号的歧义。这种写法也与 JS、Kotlin 和 Scala 的 $ 符号同构。
#2.10.14. 派生策略小结
fmt 的 trait 中只有 Debug 可以派生。Display 不是派生目标:面向用户的表面在每个领域中的决定方式不同,自动派生并不合适,而且 Display 没有有意义的默认形式。由类型的作者编写文本,可以写成 impl Display,对于 f-string 能表达的文本,也可以用 #[display("..")]。
##[display("..")]
在结构体上,#[display("text")] 通过在 self 可见的作用域中写出 f"text" 来实现 Display:#[display("line {self.line}: {self.reason}")]。字段通过 self 读取;裸字段名({line})是错误,其帮助信息会给出 {self.line}。在枚举上它适用于每个变体;否则每个变体各自带一个,变体的属性还能按名字看到该变体的具名字段,并以 _0、_1、... 看到其元组字段;只要有一个变体带了,每个变体都必须带。泛型类型的类型参数在实现中获得 Display 约束。实参是字符串字面量;插值位和说明符与 f-string 相同。
#[derive(Debug, Error)]
#[display("no key {self.key}")]
struct NotFound { key: str; }
#[derive(Debug, Error)]
enum ParseError {
#[display("line {line}: {reason}")]
Bad { line: i32; reason: str; },
#[display("empty input")]
Empty,
}
#2.10.15. Arguments:稍后格式化的 f-string
struct Arguments { .. } // Display + Debug
impl Formatter { fn write_fmt(ref self, args: Arguments) throws (FmtError); }
trait io::Write { fn write_fmt(ref self, args: fmt::Arguments) throws (IoError); } // 2.23.3
f-string 是 str(1.7.3),但在类型为 fmt::Arguments 的位置上除外:参数、带此标注的 let、字段。在那里它是 Arguments。它的插值位和动态说明符在其所在之处从左到右求值,与 str 相同;它的文本只在值被格式化时才生成,逐段写入格式化它的格式化器,从不作为一个完整的 str 生成。
- 不带说明符的插值位
{x}或{x:?}经由Display::fmt/Debug::fmt直接写入格式化器,不带调用者的说明符:大的值会分块到达from_sink格式化器(进而到达写入器)。 - 带说明符的插值位先生成自己的文本,再写出;填充和精度需要完整的文本。
- 检查与
strf-string 相同:类型没有Display(对:?而言是Debug)的插值位在该插值位处报错。
fn log(args: fmt::Arguments) { eprintln(f"[log] {args}"); }
impl Display for Point {
fn fmt(self, ref f: Formatter) throws (FmtError) { try f.write_fmt(f"({self.x}, {self.y})"); }
}
try out.write_fmt(f"{name}: {table}\n"); // table streams through its Display
log(f"{n} rows"); // n is read here; the text is made in log
Arguments 实现了 Display(其文本)和 Debug(其文本加引号,与 str 相同)。泛型位置(fn f<T: Display>(x: T))不是 Arguments 位置:f(f"..") 传递的是 str。
发现错误? 在 GitHub 上编辑此页 最后更新: