Files
pplus-web/mojo/corpus/manual/snippets/manual-values-lifetimes-3.mojo
T
2026-10-05 03:03:38 +00:00

28 lines
899 B
Mojo

var name_copy = list[2] # owned copy of list[2]
ref name_ref = list[2] # reference to list[2]
```
#### Parametric mutability of return values
Another advantage of `ref` return arguments is the ability to support parametric
mutability. For example, recall the signature of the `__getitem__()` method
above:
```mojo
def __getitem__(ref self, index: Int) raises -> ref[self] String:
```
Since the `origin` of the return value is tied to the origin of `self`, the
returned reference will be mutable if the method was called using a
mutable reference. The method still works if you have an immutable reference
to the `NameList`, but it returns an immutable reference:
```mojo
def pass_immutable_list(list: NameList) raises:
print(list[2])
# list[2] += "?" # Error, this list is immutable
def main() raises:
var list = NameList("Sophie", "Jack", "Diana")
pass_immutable_list(list)