Skip to content

Structs

Structs are custom data types that group related data together.

type Person struct {
.Name: str,
.Age: i32,
.Email: str,
};

Create struct instances using composite literal syntax with the as cast:

let person := {
.Name: "Alice",
.Age: 30,
.Email: "alice@example.com"
} as Person;
// Or with explicit type annotation
let another_person: Person = {
.Name: "Bob",
.Age: 25,
.Email: "bob@example.com"
} as Person;
let name := person.Name; // Alice
let age := person.Age; // 30

Struct fields can be public or private. Which means, they can be accessed from outside the struct’s scope. Public fields are prefixed with a capital letter, while private fields are prefixed with a lowercase letter.

import "std/io";
type Person struct {
.Name: str,
.age: i32,
.Email: str,
};
fn main() {
let person := {
.Name: "Alice",
.age: 30,
.Email: "alice@example.com"
} as Person;
io::Println("Name: {}", person.Name);
io::Println("Age: {}", person.age); // This is private and cannot be accessed directly
io::Println("Email: {}", person.Email);
}
// Anonymous struct with explicit type
let point: struct{ .X: i32, .Y: i32 } = {
.X: 10,
.Y: 20
} as struct{ .X: i32, .Y: i32 };
// Inferred anonymous struct (Ferret figures out the type)
let coordinate := {
.X: 5,
.Y: 15
}; // Type is inferred from the literal

Anonymous structs are great for one-off data grouping when you don’t need a named type.