Functions
Functions are declared with fn. Parameters are typed, and a return type is written after an arrow.
Parameters and return types
fn add(a: int, b: int) -> int {
return a + b;
}
fn main() {
print(add(2, 3));
} Returning early
fn classify(n: int) -> str {
if n > 0 {
return "positive";
} else if n < 0 {
return "negative";
} else {
return "zero";
}
}
fn main() {
print(classify(-4));
} Recursion
fn factorial(n: int) -> int {
if n <= 1 {
return 1;
}
return n * factorial(n - 1);
}
fn main() {
print(factorial(5));
} This program prints 120.
Procedures
A function without a return type performs work without producing a value.
fn greet(name: str) {
print("Hello, " + name);
}
fn main() {
greet("RUDRA");
}