61 lines
1.9 KiB
Plaintext
61 lines
1.9 KiB
Plaintext
---
|
|
title: Pointers & References
|
|
description: Explicit memory access with prefix pointer syntax and Rust-native safety.
|
|
icon: MousePointer2
|
|
---
|
|
|
|
Mist uses a prefix `*` syntax for reference types. While the symbols look like C-style pointers, they adhere strictly to Rust's ownership and borrowing rules.
|
|
|
|
## Basic Syntax
|
|
|
|
Reference types are written with `*` before the type. Use `*mut` for mutable references. The `&` and `&mut` operators create references from values.
|
|
|
|
```mist
|
|
let x i32 = 42;
|
|
let r *i32 = &x;
|
|
|
|
let mut y = 42;
|
|
let r *mut i32 = &mut y;
|
|
*r = 100;
|
|
```
|
|
|
|
In function parameters:
|
|
|
|
```mist
|
|
fn increment(value *mut i32, limit *i32) {
|
|
if (*value < *limit) {
|
|
*value = *value + 1;
|
|
}
|
|
}
|
|
```
|
|
|
|
## Lifetimes
|
|
|
|
Lifetimes are placed between `*` and the type, reading as "pointer with lifetime to type":
|
|
|
|
```mist
|
|
pub struct Inspector<'a> {
|
|
pub target *'a str,
|
|
pub counter *'a mut u32,
|
|
}
|
|
```
|
|
|
|
## Allocations
|
|
In classes, it's very important to initialize heap allocated fields in `constructor` using `path -> expr`, here is the most common example:
|
|
```mist
|
|
pub class Dog : Animal {
|
|
constructor() {
|
|
super -> Super::new();
|
|
}
|
|
}
|
|
```
|
|
This outputs `std::ptr::write` which is a force write to memory without dropping what "exists", and it's commonly used in uninitialized memory, such as uninitialized dynamic fields.
|
|
|
|
## Key Characteristics
|
|
|
|
- **Prefix Pointer Syntax**: `*Type` for shared references, `*mut Type` for mutable references.
|
|
- **Explicit Intent**: The `*mut` syntax clearly distinguishes read-only from writable references, mapping 1:1 to Rust's `&` and `&mut`.
|
|
- **Visual Consistency**: Lifetimes (`'a`) are placed before the type in `*'a Type`, keeping the declaration flow left-to-right.
|
|
- **Safety Guaranteed**: Despite the "pointer" appearance, the Mist compiler enforces Rust's borrow checker.
|
|
- **Zero Overhead**: Mist pointers compile to identical machine code as Rust references.
|