Structs
Structs are custom data types that group related data together.
Struct Definition
Section titled “Struct Definition”type Person struct { .Name: str, .Age: i32, .Email: str,};Creating Instances
Section titled “Creating Instances”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 annotationlet another_person: Person = { .Name: "Bob", .Age: 25, .Email: "bob@example.com"} as Person;Accessing Fields
Section titled “Accessing Fields”let name := person.Name; // Alicelet age := person.Age; // 30Visibility
Section titled “Visibility”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 typelet 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 literalAnonymous structs are great for one-off data grouping when you don’t need a named type.
Next Steps
Section titled “Next Steps”- Learn about Methods - Add behavior to your types
- Explore Enums - Define sets of named values
- Understand Maps - Store key-value pairs
- Master Interfaces - Define behavior contracts