29 Mut Functions
IntermediateThe instance member functions in a struct cannot modify the instance, to solve this, a mut function can be used.
By using the mut modifier before a function, the function can now modify the instance, if the created instance uses the var modifier.
Non-mut functions cannot access mut functions directly.
Mutable_Functions.cj
interface moneyStorage {
mut func addMoney(): Unit
}
struct Purse <: moneyStorage {
public var money = 0
// Without mut, this would return an error
public mut func addMoney(): Unit {
money += 1
}
}
main() {
var myPurse: Purse = Purse()
var theirPurse: moneyStorage = myPurse
theirPurse.addMoney()
println(myPurse.money)
}
// Output:
// 0