Skip to content
Kavachकवच

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
apart.kav: Kavach code, then what running it prints
  • A list is taken apart by position. A name with no item left gets none, as third does.
  • ...rest takes all the items after the others, as a list.
  • A record is taken apart by field name; age: years gives 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] = scores works on any list: a missing item becomes none, and its type says so.

    decision 0037