Version: 1.1.0
Lifetimes, origins, and references
A reference is only valid as long as the value it points at. Mojo calls that span an origin and checks that you do not keep the reference too long.
Essentials
- An argument reference lives for the function call.
- Returning a reference to a local is rejected.
- A struct method can return a reference tied to
self. - Origins compose: a reference derived from another reference cannot outlive it.
- When the checker cannot see the relationship, store an owned value instead.
Example
struct Box:
var text: String
fn borrow(ref self) -> ref [self] String:
return self.text
Keep in mind
Origins are the compile-time answer to dangling pointers. If a signature becomes hard to read, the data model is usually asking for an owned copy.