#2.10. fmt:格式化 trait
本頁內容
- 2.10.1. 分派
- 2.10.2. Formatter
- 2.10.3. Display
- 2.10.4. Debug
- Display 與 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。
refs-lang 1.7.4 f-string 格式規範中的詞法分解與本章的 trait 分派,共同決定 f-string 的意義。
#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 建立的 formatter 最多保有約一個區塊(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 與 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) 把 [file:line:col] <e's source text> = <e:?> 與換行寫到 stderr,並回傳 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 型別都透過 core::fmt 的全面實作 impl<T: Display> ToStr for T 擁有 x.to_str() -> str,即其 Display 文字(Python 的 str(x))。型別自己的 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 formatter 在其 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 相同;它的文字只在值被格式化時才產生,逐段寫入格式化它的 formatter,永遠不會成為單一個 str。
- 無規範的填空
{x}或{x:?}經由Display::fmt/Debug::fmt直接進入 formatter,不帶呼叫端的規範:大型的值會以區塊形式到達from_sinkformatter(進而到達 writer)。 - 有規範的填空會先產生自己的文字,再寫出;填補與精度需要完整的文字。
- 檢查與
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 上編輯此頁 最後更新: