Display
PrintLine("{}", value) has printed numbers, text and booleans since the very first lessons. That is not special treatment for built-in types: each of them implements one interface, Display from the Text package. A type of your own prints the same way as soon as it implements Display too. This lesson gives a Money type the text $12.05.
The Display interface
Display asks for a single method. In the Text package it is declared as below — with no receiver, like every requirement that only reads the value; an implementation adds its own &self:
func WriteDisplay(writer: &var TextWriter, spec: FormatSpec) throws FormatError;
| Part | What it is |
|---|---|
writer: &var TextWriter | Wherever the text is going — the console, a string, a buffer. An interface parameter, borrowed writable because writing moves it along. |
spec: FormatSpec | What the placeholder asked for, such as the width in {:>8}. |
throws FormatError | Writing can fail — the console may be closed, a buffer may be full — so the method can throw, with no success value, as in Unit fallible. |
These names come from two packages, so the lesson imports them, and its Rux.toml lists Format and Text:
import Format::WriteFormat;
import Io::PrintLine;
import Text::{ Display, FormatError, FormatSpec, TextWriter, WriteBytes };
Writing the text
extend Money : Display {
// `spec` carries what the placeholder asked for, such as the width in `{:>8}`. This
// implementation ignores it, which a type is free to do.
func WriteDisplay(&self, writer: &var TextWriter, spec: FormatSpec) throws FormatError {
var cents = self.cents;
if cents < 0 {
// One write that may fail. `try` hands an error to the caller and stops here.
try WriteBytes(writer, "-");
cents = -cents;
}
// `WriteFormat` is PrintLine's twin: the same placeholders, written into the writer.
// `{:02}` pads the cents to two digits with zeros, so 5 cents shows as `05`.
try WriteFormat(writer, "${}.{:02}", cents / 100, cents % 100);
}
}
The method is built from two writes, and either may fail. Each one is marked with try, as in Propagate:
try WriteBytes(writer, "-")writes the minus sign. If the write throws,trypasses theFormatErrorstraight on to the caller and the method stops there.try WriteFormat(…)writes the rest in the same way. When it succeeds, the method reaches its end, and reaching the end is its success — there is nothing toreturn.
WriteFormat takes the same placeholders as PrintLine. Here {:02} pads the cents to two digits, so 5 cents becomes 05 and the coin prints as $0.05.
What happens when you print
flowchart LR
p["`PrintLine` with a `{}`<br/>and a `Money`"] --> d["`Money`'s `WriteDisplay`"]
d --> w1["`WriteBytes`: `'-'`<br/>(only when negative)"]
w1 --> w2["`WriteFormat`: `'$12.05'`"]
w2 --> out["the console"]
w1 -.->|"a thrown error<br/>leaves early"| pPrintLine checks every argument against Display — it borrows each one as a &Display view, as Interface value showed. Money now passes, so it goes into a placeholder like any number would:
PrintLine("price: {}", price);
PrintLine("refund: {}", refund);
PrintLine("coin: {}", coin);
PrintLine("{} back from {}", refund, price);
Ignoring the spec
spec carries the placeholder's width, alignment, fill and precision. Money ignores it, which a type is free to do, but it has a visible effect: PrintLine("[{:>10}]", price) prints [$12.05] with no padding, because nothing in WriteDisplay applies the width. The Format lesson covers what those placeholder options mean.
The program
The whole lesson is one package in the Examples repository. Its comments explain every step.
// `PrintLine("{}", value)` prints numbers, text and booleans because each of those types
// implements one interface, `Display` from the Text package. A type of your own prints the same
// way as soon as it implements `Display` too.
//
// `Display` asks for a single method, `WriteDisplay`. It is handed a writer, which stands for
// wherever the text is going, and it writes the value's text into it. Writing can fail (the
// console may be closed, a buffer may be full), so the method declares `throws FormatError`, and
// every write in it is marked with `try`, which passes an error from any step straight on.
import Format::WriteFormat;
import Io::PrintLine;
import Text::{ Display, FormatError, FormatSpec, TextWriter, WriteBytes };
// An amount of money, kept as whole cents so nothing is lost to rounding.
struct Money {
cents: int64;
}
extend Money : Display {
// `spec` carries what the placeholder asked for, such as the width in `{:>8}`. This
// implementation ignores it, which a type is free to do.
func WriteDisplay(&self, writer: &var TextWriter, spec: FormatSpec) throws FormatError {
var cents = self.cents;
if cents < 0 {
// One write that may fail. `try` hands an error to the caller and stops here.
try WriteBytes(writer, "-");
cents = -cents;
}
// `WriteFormat` is PrintLine's twin: the same placeholders, written into the writer.
// `{:02}` pads the cents to two digits with zeros, so 5 cents shows as `05`.
try WriteFormat(writer, "${}.{:02}", cents / 100, cents % 100);
}
}
func Main() -> int {
let price = Money { cents: 1205 };
let refund = Money { cents: -350 };
let coin = Money { cents: 5 };
// Now Money goes into a placeholder like any number would.
PrintLine("price: {}", price);
PrintLine("refund: {}", refund);
PrintLine("coin: {}", coin);
PrintLine("{} back from {}", refund, price);
// Take away the `extend` and every line above is refused, the first with "no matching
// overload for 'PrintLine' with argument types (char8[..], Money)".
return 0;
}
Besides Io, its Rux.toml lists Format and Text under [Dependencies].
Run it
cd Examples/Interfaces/Display
rux run
price: $12.05
refund: -$3.50
coin: $0.05
-$3.50 back from $12.05
Common mistakes
Try it yourself
- Give
struct Point { x: int32; y: int32; }aDisplaythat prints(1, 2). - Print
pricewithPrintLine("[{:>10}]", price)and explain why no padding appears. - Make a
Temperaturewith acelsius: int32field print as21 C, and-4 Cbelow zero.