Learn Aero / Functions
Functions
Defining a Function
fn add(a: i64, b: i64) -> i64 {
return a + b;
}
print(add(1, 2)); // 3fn declares a function; (a: i64, b: i64) is the parameter list; -> i64 is the return type; return returns a valueFunctions Without a Return Value
The return type can be omitted:
fn greet(name: i64) {
print("hello %d\n", name);
}
greet(7); // hello 7Arguments Are Passed by Value
Changing a parameter inside a function does not affect the caller's variable:
fn bump(n: i64) {
n = n + 1;
print("inside: %d\n", n); // inside: 11
}
let x = 10;
bump(x);
print("outside: %d\n", x); // outside: 10,没变To change the caller's variable, use a reference (see References & Borrowing) or return a new value.
Recursion
Aero allocates a 64MB stack for recursion (default ~1MB), so tens of thousands of levels can be safely recursed:
fn fact(n: i64) -> i64 {
if (n <= 1) { return 1; }
return n * fact(n - 1);
}
print(fact(5)); // 120Forward Calls: Functions Can Be Defined Later
The compiler does two passes — it collects signatures first, then generates code — so functions can call each other:
fn is_even(n: i64) -> i64 {
if (n == 0) { return 1; }
return is_odd(n - 1);
}
fn is_odd(n: i64) -> i64 {
if (n == 0) { return 0; }
return is_even(n - 1);
}
print(is_even(10)); // 1(真)Scoping Rules
fn inside a function bodyfn outer() {
// fn inner() {} // 错误:不允许嵌套定义
}The Nuances of return
-> i64 is declared, return must carry a valuereturn cannot carry a valuefn f() -> i64 {
return 1; // 必须带值
}
fn g() {
return; // 空 return,提前结束
}