Function Basics¶
Functions are reusable blocks of code that perform specific tasks.
Defining Functions¶
Use the fn keyword to define a function:
Functions with Parameters¶
fn greet(name) {
print "Hello, #{name}!";
}
greet("Alice"); // Hello, Alice!
greet("Bob"); // Hello, Bob!
Multiple Parameters¶
Return Values¶
Use return to send a value back to the caller:
Early Return¶
fn divide(a, b) {
if b == 0 {
print "Error: Division by zero";
return 0;
}
return a / b;
}
print divide(10, 2); // 5
print divide(10, 0); // 0 (with error message)
Function Examples¶
Calculator Functions¶
fn multiply(a, b) {
return a * b;
}
fn subtract(a, b) {
return a - b;
}
let product = multiply(4, 5);
let difference = subtract(10, 3);
print product; // 20
print difference; // 7
String Functions¶
fn make_greeting(name, time_of_day) {
let greeting = "Good #{time_of_day}, #{name}!";
return greeting;
}
print make_greeting("Alice", "morning");
print make_greeting("Bob", "evening");
Validation Function¶
fn is_valid_age(age) {
if age < 0 {
return false;
}
if age > 150 {
return false;
}
return true;
}
if is_valid_age(25) == true {
print "Valid age";
}
Calling Functions¶
fn calculate_area(width, height) {
return width * height;
}
// Direct call
print calculate_area(5, 10); // 50
// Store result
let area = calculate_area(8, 12);
print area; // 96
// Use in expression
let total_area = calculate_area(5, 5) + calculate_area(3, 3);
print total_area; // 34
Scope¶
Functions have their own scope: