103 lines
2.0 KiB
Plaintext
103 lines
2.0 KiB
Plaintext
---
|
|
title: Functions
|
|
description: Defining execution blocks with C-style ergonomics and Rust-powered safety.
|
|
icon: SquareFunction
|
|
---
|
|
|
|
Functions are the primary unit of execution in Mist, using C-style syntax with the return type before the name. The last expression in a block is implicitly returned.
|
|
|
|
## Basic Syntax
|
|
|
|
Functions place the return type before the name, followed by parameters in parentheses.
|
|
|
|
```mist
|
|
void greet() {
|
|
println!("Hello!");
|
|
}
|
|
|
|
i32 add(i32 a, i32 b) {
|
|
a + b
|
|
}
|
|
```
|
|
|
|
## Visibility & Modules
|
|
|
|
Functions use `pub` for public visibility. Files declare a module with `pub module name;`.
|
|
|
|
```mist
|
|
pub module utils;
|
|
|
|
pub i32 get_version() {
|
|
1
|
|
}
|
|
|
|
pub void process() {
|
|
// ...
|
|
}
|
|
```
|
|
|
|
## Mutable Parameters
|
|
|
|
Use `mut` after the type to allow reassignment within the function body.
|
|
|
|
```mist
|
|
void update_score(i32 mut current_score, i32 bonus) {
|
|
current_score = current_score + bonus;
|
|
}
|
|
```
|
|
|
|
## Methods & `&self`
|
|
|
|
Methods take `&self` (immutable) or `&mut self` (mutable) as the first parameter.
|
|
|
|
```mist
|
|
struct Counter {
|
|
i32 value,
|
|
}
|
|
|
|
impl Counter {
|
|
pub i32 get(&self) {
|
|
self.value
|
|
}
|
|
|
|
pub void increment(&mut self) {
|
|
self.value += 1;
|
|
}
|
|
}
|
|
```
|
|
|
|
## Closures
|
|
|
|
Closures are anonymous functions defined with arrow syntax:
|
|
|
|
```mist
|
|
let add = (a, b) => a + b;
|
|
add(2, 3);
|
|
|
|
// With a block body
|
|
let greet = (name str&) => {
|
|
println!("Hello {}", name);
|
|
};
|
|
```
|
|
|
|
## Attributes & Metadata
|
|
|
|
Metadata is applied via the `#[attr]` syntax directly above the declaration.
|
|
|
|
```mist
|
|
#[inline]
|
|
pub i32 clamp(i32 value, i32 min, i32 max) {
|
|
if value < min { min }
|
|
else if value > max { max }
|
|
else { value }
|
|
}
|
|
```
|
|
|
|
## Key Characteristics
|
|
|
|
- **C-Style Syntax**: Return type before name — no `fn` keyword.
|
|
- **Implicit Returns**: The final expression in a block is automatically returned.
|
|
- **`&self` / `&mut self`**: Explicit self parameter in method definitions.
|
|
- **Closure Support**: Arrow syntax `(params) => expr` for anonymous functions.
|
|
- **Zero-Cost Mapping**: Every function maps directly to a Rust `fn`.
|