docs

你正在阅读 v0.1.2 的文档。Nabi 0.1.2 已不再提供支持。 最新版本:v0.1.3 →

本页尚未翻译,以下为英文原文。

#CSV report

本页内容

Write a small sales CSV to a temporary file, read it back line by line, and print a per-region summary table with aligned columns.

#Code

#Walkthrough

  • The file is created under env::temp_dir() and removed in the finally of main, so no temporary file is left behind even if summarizing fails (Files and I/O, env::temp_dir).
  • Writing goes through a BufWriter and reading through a BufReader, each bound with using (using): the statement using w = ..; in write_csv closes the file when the function's block ends, the block form in summarize when its block ends, and the writer writes out what it still holds first, so a failed write is never lost. r.lines() is a fallible iterator, so try for takes each line and passes a read error on (BufReader, fs).
  • parse_row throws a RowError for a malformed row; the caller prints a warning in its catch block and moves on with continue. One bad line does not sink the whole report (Errors).
  • The totals are a Dict<str, Group>, typed by summarize's return type. groups[region, default: Group {}].orders += 1 starts a new entry when the region is missing, and the lines after it add to the stored entry in place. Every field of Group has a default, so Group {} alone starts at zero (Collections and iterators).
  • Format specs line up the table: {name:<8} left-aligns, {g.revenue:>9.2} uses width 9 and two decimals, and {"":-<8} fills an empty string with - to draw the rule (2.10.8 align and width).

Found a mistake? Edit this page on GitHub. Last updated