Antra

Standardbibliothek

Antra::Display

import Antra::Display

Display protocol behind str(...), print/println and string interpolation.

By default those render a value structurally (%Wallet{ :cents => 95000 }). An implementation of __str__ replaces that with a form of your own:

import Antra::Display.*

package Wallet with Display {
    pub fn new(c) -> bless(%{cents: c}, Wallet)
    fn __str__(self) -> str(self.cents / 100) <> " EUR"
}

println(Wallet.new(95000))   # 950 EUR

The hook applies wherever a value is rendered FOR A READER, nested values included (println([w1, w2])). It deliberately does NOT apply to dd(...) or to error messages and other diagnostics: those must show what the value really holds, and a broken __str__ must not swallow the message it appears in.

Überblick#

Bestimmt, wie ein Wert sich zeigt. str(...), print/println und die String-Interpolation rendern sonst die Struktur (%Wallet{ :cents => 95000 }); ein __str__ ersetzt das:

import Antra::Display.*

package Wallet with Display {
    pub fn new(c) -> bless(%{cents: c}, Wallet)
    fn __str__(self) -> str(self.cents / 100) <> " EUR"
}

println(Wallet.new(95000))            # 950 EUR
println([Wallet.new(100)])            # [1 EUR]

Das Paket enthaelt nur das Protokoll (fn __str__(self)) — noetig ist der Import nicht, jedes eigene Protokoll mit dieser Methode wirkt genauso.

Zwei Dinge nutzen den Hook bewusst nicht: dd(...) und Fehlermeldungen. Die sollen zeigen, was wirklich im Wert steht. Und __str__ muss einen String zurueckgeben und darf nicht str(self) auf sich selbst aufrufen; beides meldet Antra klar, statt in einen Stack-Overflow zu laufen.

Protokolle#

Displayprotocol</>
protocol Display {
    fn __str__(self) :- String
}

Values that render themselves for a reader.

Quelle dieser Seite