Anonymous Records
Also known as: anonymous record named tuple object literal inline struct alias
● Intermediate4 minBefore this: Records, TuplesSpec 2.14
(times: 3, wait_ms: 200) is a record written on the spot, with no type declared for it.
fn minmax(xs: [Int]) -> (lo: Int, hi: Int) {
(lo: xs.min() ?? 0, hi: xs.max() ?? 0)
}
fn main() {
const r = minmax([3, 1, 4])
print("lo {r.lo}, hi {r.hi}")
const retry = (times: 3, wait_ms: 200)
print(retry.times)
}The program ran and printed:
kavach run anon.kav
lo 1, hi 43
A function can give back several named values: r.lo reads better than the position in a tuple. Two anonymous records with the same fields fit each other, in any order. Name the shape with an alias when you use it often:
type Retry = (times: Int, wait_ms: Int)
fn describe(r: Retry) -> String {
"{r.times} tries, {r.wait_ms} ms apart"
}
fn main() {
print(describe((times: 3, wait_ms: 200)))
print(describe((wait_ms: 50, times: 5)))
}The program ran and printed:
kavach run alias.kav
3 tries, 200 ms apart5 tries, 50 ms apart
Start with an anonymous record while a design settles; turn it into a type when it needs methods.