Learn Aero / Functions

Functions

Defining a Function

fn add(a: i64, b: i64) -> i64 {
    return a + b;
}

print(add(1, 2));   // 3
  • fn declares a function; (a: i64, b: i64) is the parameter list; -> i64 is the return type; return returns a value
  • Functions Without a Return Value

    The return type can be omitted:

    fn greet(name: i64) {
        print("hello %d\n", name);
    }
    greet(7);   // hello 7

    Arguments 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));   // 120

    Forward 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

  • The function body is an independent block; variables inside are not visible outside
  • Parameters can be reassigned inside the function
  • Function definitions cannot be nested: you cannot write another fn inside a function body
  • fn outer() {
        // fn inner() {}   // 错误:不允许嵌套定义
    }

    The Nuances of return

  • If -> i64 is declared, return must carry a value
  • If no return type is declared, return cannot carry a value
  • fn f() -> i64 {
        return 1;   // 必须带值
    }
    fn g() {
        return;     // 空 return,提前结束
    }
    Aero 文档 · 基于 Aero 1.2.0 文档整理 · MIT
    SereinTeam