Records
Also known as: struct class object union enum variant pattern matching match switch case tagged immutable update copy
● Intermediate5 minBefore this: Data Types, FunctionsSpec 2.4
A record is a type of your own: named fields grouped under one name, such as a User with a name and an age.
Syntax
type Name {
field: Type
other: Type = default
}Example
type User {
name: String
age: Int
city: String = "Pune"
}
fn main() {
const asha = User(name: "Asha", age: 31)
print("{asha.name}, {asha.age}, {asha.city}")
const older = asha with { age: 32 }
print("{asha.age} -> {older.age}")
let copy = asha
copy.city = "Delhi"
print("{asha.city} / {copy.city}")
}The program ran and printed:
kavach run record.kav
Asha, 31, Pune31 -> 32Pune / Delhi
type User { … }declares the record;User(name: …, age: …)makes one, naming every field.asha.namereads a field.- A record is a value:
copychanging its city leavesashaas she was.
Other languages call this a struct, or a class with only data.
One page for each form
Try it yourself
Declare a
Book with a title and a number of pages, make one, and print its title.Show the answer
type Book { title: String pages: Int } (one field per line), then const b = Book(title: "Gitanjali", pages: 103) and print(b.title).
What Kavach does for you
Small records live in registers
A record nobody else holds needn't be built in memory at all: its fields can stay in CPU registers.