Files
mist-website/content/docs/components/traits.mdx
T
2026-06-28 22:45:01 +02:00

71 lines
1.6 KiB
Plaintext

---
title: Traits
description: Defining shared behavior and contracts with Mist's signature ergonomics.
icon: Sparkles
---
Traits in Mist define a set of methods that a type must implement, facilitating polymorphism and shared behavior. Method signatures use C-style syntax with `&self` for the instance parameter.
## Defining a Trait
A trait lists method signatures using return-type-first syntax, with `&self` as the instance parameter.
```mist
pub trait Drawable {
void draw(&self);
str& metadata(&self);
}
```
## Implementing a Trait
Use `impl Trait for Type` to provide implementations:
```mist
impl Drawable for Task {
void draw(&self) {
println!("Drawing task: {}", self.name);
}
str& metadata(&self) {
self.name
}
}
```
## Default Implementations
Traits can provide default behavior for methods that implementing types may override:
```mist
pub trait Identifiable {
u32 get_id(&self);
bool is_valid(&self) {
self.get_id() > 0
}
}
```
## Super-traits
A trait can require another trait using the colon `:` syntax:
```mist
pub trait Speak {
String speak(&self);
}
pub trait Greet : Speak {
String greet(&self);
}
```
## Key Characteristics
- **C-Style Signatures**: Return type before name — no `fn` keyword.
- **Explicit Context**: Methods use `&self` as the first parameter, mapping directly to Rust's reference rules.
- **Default Methods**: Traits can provide default implementations.
- **Super-traits**: Colon syntax for expressing trait requirements.
- **Static Dispatch**: By default, Mist traits leverage Rust's zero-cost generics and monomorphization.