Heroes / Examples / 12-interpolation
examples/gallery/12-interpolation.hero
Put a value inside a string, and let the compiler say when it has no text.
- 33 lines
An f before the opening quote lets a string carry values: f"{at}/{of} {star.name}" writes each hole as to_str would write it. Any expression may stand in a hole, including a call or another string of the same kind; {{ writes one opening brace, and outside a hole a closing brace is not special. A hole may hold what to_str can render: an integer, a float, bool or str. A record, an array or a value that may be missing is refused at the hole, and the note says what to write instead.
Run it
These files introduce the language one feature at a time. This page shows the program and not a result, because no test compares their output byte for byte yet.
The program
## 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"}")
fingerprint sha256 e7de07131795 · 1 file · index.json
Next: 13-lease. All the examples. ← Previous: 11-trees
Run one yourself: the four commands. Learn the language, or read the full specification in one file.