Variables: Destructuring
● Beginner5 min
Take a list, a record or a map apart into several names in one line.
type User {
name: String
age: Int
city: String?
}
fn main() {
const [first, second, third] = [90, 75]
print("{first} {second} {third}")
const [head, ...rest] = ["asha", "ravi", "mei"]
print("{head} then {rest}")
const u = User(name: "Asha", age: 31, city: none)
const { name, age: years, city = "unknown" } = u
print("{name}, {years}, {city}")
const settings = ["host": "example.com"]
const [host, port = "8080"] = settings
print("{host}:{port}")
const [_, [x, y]] = [[1, 2], [3]]
print("{x} {y}")
}The program ran and printed:
kavach run apart.kav
90 75 noneasha then ["ravi", "mei"]Asha, 31, unknownexample.com:80803 none
- A list is taken apart by position. A name with no item left gets
none, asthirddoes. ...resttakes all the items after the others, as a list.- A record is taken apart by field name;
age: yearsgives the field another name. = "8080"is a default, used when the value is missing._skips an item you don't need.
What Kavach does for you
Taking values apart is typed
const [first, second] = scoresworks on any list: a missing item becomesnone, and its type says so.