For example, if I pass a record (with mutable fields) as an argument to a function, will the function be able to mutate the original record?
(I suppose I could try this myself, but I wanted to get official clarification as well.)
For example, if I pass a record (with mutable fields) as an argument to a function, will the function be able to mutate the original record?
(I suppose I could try this myself, but I wanted to get official clarification as well.)
It passes the reference.
I would rephrase this. By-value and by-reference are notions of more low-level languages. In Motoko, there is no observable difference, it is an implementation detail.
Instead, some values are mutable. But a mutable value has identity and is never implicitly copied, no matter what you do with it (because copying would in fact create a different value).
See also my reply here.
Instead, some values are mutable . But a mutable value has identity and is never implicitly copied, no matter what you do with it (because copying would in fact create a different value).
To clarify, does this mean that a function like this works as expected:
func foo(arg : { var bar : Nat }) {
arg.bar := 10;
};
How about if I wanted to pass a mutable value directly to a function and mutate it within the body of the function?
For example, the compiler complains when I do this:
func foo(var s : Nat) {
s := 10;
};
In lower-level languages, I could pass a pointer and mutate its contents, but is there an equivalent in Motoko? Or do I need to wrap the mutable variable in a record (as a mutable field), like in the first example?
Yes. In other words, mutable variables are not “first class”.