68 lines
1.6 KiB
Plaintext
68 lines
1.6 KiB
Plaintext
---
|
|
title: Pointers & References
|
|
description: Explicit memory access with postfix reference syntax and Rust-native safety.
|
|
icon: MousePointer2
|
|
---
|
|
|
|
Mist uses a postfix `&` syntax for reference types. While familiar from C++, these references adhere strictly to Rust's ownership and borrowing rules.
|
|
|
|
## Basic Syntax
|
|
|
|
Reference types are written with `&` after the type. Use `mut&` for mutable references. The `&` and `&mut` operators create references from values.
|
|
|
|
```mist
|
|
i32 x = 42;
|
|
i32& r = &x;
|
|
|
|
let mut y = 42;
|
|
i32 mut& r = &mut y;
|
|
*r = 100;
|
|
```
|
|
|
|
In function parameters:
|
|
|
|
```mist
|
|
void increment(i32 mut& value, i32& limit) {
|
|
if *value < *limit {
|
|
*value = *value + 1;
|
|
}
|
|
}
|
|
```
|
|
|
|
## Lifetimes
|
|
|
|
Lifetimes are placed before the type in the `&` suffix:
|
|
|
|
```mist
|
|
pub struct Inspector<'a> {
|
|
&'a str target,
|
|
&'a mut u32 counter,
|
|
}
|
|
```
|
|
|
|
## In Classes
|
|
|
|
Methods use `&self` for immutable access and `&mut self` for mutable access:
|
|
|
|
```mist
|
|
pub class Logger {
|
|
String prefix;
|
|
|
|
pub void info(&self, message str&) {
|
|
println!("{}", message);
|
|
}
|
|
|
|
pub void reset(&mut self) {
|
|
self.prefix = String::new();
|
|
}
|
|
}
|
|
```
|
|
|
|
## Key Characteristics
|
|
|
|
- **Postfix Reference Syntax**: `T&` for shared references, `T mut&` for mutable references.
|
|
- **Explicit Intent**: The `mut&` syntax clearly distinguishes read-only from writable references.
|
|
- **Visual Consistency**: Lifetimes (`'a`) are placed before the type in `&'a T`.
|
|
- **Safety Guaranteed**: The Mist compiler enforces Rust's borrow checker.
|
|
- **Zero Overhead**: Mist references compile to identical machine code as Rust references.
|