I have a question regarding the behavior of the reg
argument (when the keyword reg
is used as the argument convention). The question arises from the following code that won’t compile in Mojo v25.4.
def changit(ref a: Int):
a = 10
def main():
var a = 1
changit(a)
The error message is:
error: expression must be mutable in assignment
a = 10
^
This suggests that the ref
keyword is equivalent to the read
keyword in this case.
However, I also noticed the following facts:
ref
can be used to let the argument carry parametric mutability. So that you can do something like printing the mutability of the origin, e.g.,def is_mutable[ mutability: Bool, //, origin: Origin[mutability] ](ref [origin]x: Int): print("The value is mutable?", mutability) def main(): var a = 10 is_mutable(a)
- The reference created by the
ref
keyword in a local scope can be mutable. For example,def main(): var a = 1 ref b = a b = 10
- The
ref
keyword is used in a loop to make that the element mutable. For example,def main(): var lst = [1, 2, 3] for ref i in lst: i += 1
Then, a question comes into my mind: why is the argument a
in the function def changit(ref a: Int)
immutable?
I have several guesses:
- This feature will change in future, so that
ref
argument can be mutable in case the origin is mutable. In other words,ref
will either work asread
ormut
. - This is the desired behavior of
ref
. It just contains mutability information of the origin, but is not mutable in the scope, which means that it behaviors asread
.
Can anyone help me verify my propositions? Thank you very much in advance!