Skip to content
Kavachकवच

Variables: Changing a value

● Beginner3 min

Give a let a new value with =, or change it in place with +=, -=, *= and the others.

fn main() {
    let score = 10
    score = score + 5
    score *= 2
    score -= 1
    print(score)
}

The program ran and printed:

kavach run change.kav

29
change.kav: Kavach code, then what running it prints

score *= 2 is short for score = score * 2, and is checked the same way: a result too big for an Int stops the program with a message instead of turning into a wrong number.

let makes a new one

Writing let again inside a loop doesn't change the variable outside it: it makes a new one, which is gone at the end of each turn. The total stays 0, and the compiler says why:

fn main() {
    let total = 0
    for i in 1..=2 {
        let total = total + i
    }
    print(total)
}

The compiler warned, then the program ran:

kavach run hiding-let.kav

warning: `total` is never used: this makes a new `total`, hiding the one declared above. To change that one, write `total = …` without `let` (spec 1.4)0
hiding-let.kav: Kavach code, then what running it prints

Write total = total + i, without let, and it prints 3. The editor offers that change as the quick fix "Change the total declared above". You might have meant a new variable after all, so kavach fix never makes it for you.