Struct Definition
Structs are custom data types that group related values together. They’re one of Fe’s primary tools for organizing data and behavior.
Basic Syntax
Section titled “Basic Syntax”Define a struct with the struct keyword:
struct Point { x: u256, y: u256,}Each field has a name and a type, separated by a colon.
Field Visibility
Section titled “Field Visibility”By default, struct fields are private. Use pub to make them publicly accessible:
struct Token { pub name: String, // Public - accessible from outside pub symbol: String, // Public pub decimals: u8, // Public internal_id: u256, // Private - only accessible within the module}Public Structs
Section titled “Public Structs”Make the entire struct public with pub struct:
pub struct TokenInfo { pub name: String, pub total_supply: u256,}A pub struct can be used by other modules, but its fields still need individual pub modifiers to be accessible.
Creating Instances
Section titled “Creating Instances”Create struct instances using struct literal syntax:
let point = Point { x: 10, y: 20 }All fields must be provided:
let rect = Rectangle { width: 100, height: 50,}Accessing Fields
Section titled “Accessing Fields”Access fields with dot notation:
let p = Point { x: 10, y: 20 }let x_value = p.x // 10let y_value = p.y // 20Updating Structs
Section titled “Updating Structs”Structs are immutable by default. To modify, use mut:
let mut p = Point { x: 10, y: 20 }p.x = 30 // Now p is { x: 30, y: 20 }Nested Structs
Section titled “Nested Structs”Structs can contain other structs:
struct Bounds { min: Point, max: Point,}
let bounds = Bounds { min: Point { x: 0, y: 0 }, max: Point { x: 100, y: 100 },}
let min_x = bounds.min.x // 0Structs with Complex Types
Section titled “Structs with Complex Types”Structs can hold any Fe type:
struct GameState { score: u256, position: (u256, u256), // Tuple active: bool,}
struct Registry { entries: StorageMap<u256, u256>, // For storage structs count: u256,}Destructuring
Section titled “Destructuring”Extract fields with pattern matching:
let p = Point { x: 10, y: 20 }
// Destructure into variableslet Point { x, y } = p
// Rename during destructuringlet Point { x: horizontal, y: vertical } = Point { x: 10, y: 20 }
// Partial destructuringlet Point { x, .. } = Point { x: 10, y: 20 }Structs vs Contracts
Section titled “Structs vs Contracts”An important distinction in Fe:
| Feature | Structs | Contracts |
|---|---|---|
| Fields | ✓ | ✓ |
| Impl blocks | ✓ | ✗ |
| Methods | ✓ | ✗ |
| Init block | ✗ | ✓ |
| Recv blocks | ✗ | ✓ |
Structs are for data and behavior. Contracts are for on-chain state and message handling.
Summary
Section titled “Summary”| Syntax | Description |
|---|---|
struct Name { } | Define a struct |
pub struct | Public struct |
pub field: Type | Public field |
Name { field: value } | Create instance |
instance.field | Access field |
let Name { field } = instance | Destructure |