Duration Arithmetic
Because durations are simply i64, the operators +, -, *, and / work
without conversions. This makes compositions like ttl = 2h + 30min or
interval * 2 idiomatic and immediate.
Addition combines independent durations into a total:
Duration composition, "time remaining", scaling by a scalar, a fraction of an
interval, and comparisons with == and >.
02-arithmetic.zolo
// Feature: arithmetic between durations
// Syntax: `+ - * /` work directly between literals and durations
// When to use: compose durations (ttl = 2h + 30min), scale (interval
// * 2), slice (timeout / 4). Since everything is `i64 ms` underneath,
// nothing is surprising.
// Sum of durations.
let ttl = 7200000 + 1800000 + 45000
print(ttl)
// expected: 9045000
// Subtraction — useful for "remaining time".
let limit = 3600000
let spent = 900000
let remaining = limit - spent
print(remaining)
// expected: 2700000 (45min in ms)
// Multiplication by scalar — scaling intervals.
let interval = 30000
let twice = interval * 2
print(twice)
// expected: 60000
// Division by scalar — slices.
let total = 3600000
let quarter = total / 4
print(quarter)
// expected: 900000 (15min in ms)
// Comparisons — work because both are numbers.
let a = 1000
let b = 1000
if a == b {
print("1s == 1000ms")
}
// expected: 1s == 1000ms
if 300000 > 30000 {
print("minutes > seconds")
}
// expected: minutes > seconds
Comparisons also work naturally: elapsed > 5s is equivalent to
elapsed > 5000. There is no operator overloading — it is plain integer
arithmetic.
Challenge
Calculate how much time remains to reach 2 hours, knowing that 45min + 20s
have already passed. Print the result in milliseconds.
See also