Values, Not References
Also known as: value semantics copy reference aliasing mutable shared pointer
● Advanced4 minBefore this: Lists, RecordsSpec 6.1
Every value in Kavach is a value: assigning or passing it never makes two names share it.
fn main() {
let a = [1, 2, 3]
let b = a
b.push(4)
print(a)
print(b)
}The program ran and printed:
kavach run values.kav
[1, 2, 3][1, 2, 3, 4]
b = a gives b its own list. Changing b can't change a. The same holds when you pass a value to a function:
fn add_bonus(scores: [Int]) -> [Int] {
let changed = scores
changed.push(100)
changed
}
fn main() {
const mine = [70, 80]
const theirs = add_bonus(mine)
print(mine)
print(theirs)
}The program ran and printed:
kavach run values-fn.kav
[70, 80][70, 80, 100]
In Python, Java or JavaScript, b = a makes two names for one list, and a change through one shows up in the other. That "who else changed my list?" bug can't happen here.
Four levels of control
| Level | You write | Use it for |
|---|---|---|
| 1. Automatic | nothing | almost all code |
| 2. Shared state | Shared<T> | state several parts of a program change |
| 3. Arenas | arena { … } | many short-lived values in a hot path |
| 4. Unsafe | unsafe { … } | raw memory and C |
What Kavach does for you
Copies are safe, and cheap
Assigning a list gives an independent value, so changing one never changes another. It is only really copied if one of them changes.