Husk Examples

Learn Husk through practical, real-world examples

Basic Examples

Hello World

The classic first program in Husk

fn main() {
    println("Hello, World!");
}

Variables and Types

Working with basic data types and variables

fn main() {
    let name = "Alice";
    let age = 30;
    let height = 5.6;
    let is_student = false;
    
    println(format!("{} is {} years old", name, age));
    println(format!("Height: {} feet", height));
    println(format!("Student: {}", is_student));
}

Functions

Defining and calling functions with parameters

fn add(x: int, y: int) -> int {
    x + y
}

fn greet(name: string) -> string {
    format!("Hello, {}!", name)
}

fn main() {
    let sum = add(5, 3);
    println(format!("5 + 3 = {}", sum));
    
    let message = greet("Husk");
    println(message);
}

Intermediate Examples

Structs and Methods

Creating custom types with structs and implementing methods

struct Rectangle {
    width: float,
    height: float,
}

impl Rectangle {
    fn area(self) -> float {
        self.width * self.height
    }
    
    fn perimeter(self) -> float {
        2.0 * (self.width + self.height)
    }
}

fn main() {
    let rect = Rectangle {
        width: 10.0,
        height: 5.0,
    };
    
    println(format!("Area: {}", rect.area()));
    println(format!("Perimeter: {}", rect.perimeter()));
}

Error Handling with Result

Safe error handling using the Result type

fn parse_number(s: string) -> Result<int, string> {
    // In real Husk, this would use proper parsing
    if s == "42" {
        Result::Ok(42)
    } else {
        Result::Err("Invalid number")
    }
}

fn main() {
    let input = "42";
    
    match parse_number(input) {
        Result::Ok(num) => {
            println(format!("Parsed: {}", num));
        },
        Result::Err(msg) => {
            println(format!("Error: {}", msg));
        }
    }
}

Find more examples in the GitHub repository

View All Examples