Heroes / Esempi / 12-interpolation
examples/gallery/12-interpolation.hero
Mettere un valore dentro una stringa, e lasciare che il compilatore dica quando non ha un testo.
- 33 righe
Una f prima della virgoletta d’apertura permette a una stringa di portare dei valori: f"{at}/{of} {star.name}" scrive ogni buco come lo scriverebbe to_str. In un buco può stare qualsiasi espressione, compresa una chiamata o un’altra stringa dello stesso tipo; {{ scrive una graffa aperta, e fuori da un buco la graffa chiusa non è speciale. Un buco può contenere ciò che to_str sa rendere: un intero, un numero con la virgola, un bool o una str. Un record, un array o un valore che potrebbe mancare vengono rifiutati al buco, e la nota dice cosa scrivere al loro posto.
Eseguilo
Questo esempio serve a illustrare il linguaggio. Qui trovi il programma e non un risultato: non ci sono ancora test che confrontino il suo output byte per byte.
Il programma
## Text with holes in it
#
# An `f` before the opening quote lets a string carry values: `{n}` writes `n`
# as `to_str` would. Any expression may stand in a hole — a sum, a call, a
# field, another `f"…"` — and the hole ends at the `}` that closes it, so a
# map index or a nested literal inside it is read as it would be anywhere.
# `{{` and `}}` each write one brace, and a `}` alone is an error. A literal
# without the `f` prints its braces as they stand, and is refused where they
# hold what would be a hole naming only what is bound there: `"{n}"` is a
# forgotten `f` whenever `n` is.
#
# What a hole may hold is what `to_str` renders: an integer, a float, `bool`
# or `str`. A record or an array has no text of its own, and a map index
# answers a `V?` that must be made whole first — `check` says so, at the hole.
record Star
name: str
magnitude: f64
function line(at: i64, of: i64, star: Star) -> str
return f"{at}/{of} {star.name} at magnitude {star.magnitude}"
function main()
stars = [Star(name: "Sirius", magnitude: -1.46), Star(name: "Vega", magnitude: 0.03)]
at: i64 @= 1
for star in stars
print(line(at: at, of: stars.len(), star: star))
at @ at + 1
seen: {str: i64} = {"Sirius": 2}
print(f"seen Sirius {seen["Sirius"].must()} times, {{like this}}")
print(f"nested: {f"{stars.len()} stars"}")
impronta sha256 e7de07131795 · 1 file · index.json
Successivo: 13-lease. Tutti gli esempi. ← Precedente: 11-trees
Eseguine uno: i quattro comandi. Impara il linguaggio, oppure leggi la specifica completa in un solo file.