Files
pplus-library/mojo/corpus/manual/snippets/manual-values-lifetimes-3.mojo
T
alexm 568474d52f
Test (in pplus-core) / in-core (push) Failing after 28m44s
Initial commit
2026-11-12 22:23:48 -05:00

28 lines
899 B
Mojo
Generated

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)