توابع

fn gcd(a: u32, b: u32) -> u32 {
    if b > 0 {
        gcd(b, a % b)
    } else {
        a
    }
}

fn main() {
    println!("gcd: {}", gcd(143, 52));
}
This slide should take about 3 minutes.
  • بعد اعلان تابع پارامترهای ورودی و نوع آن و سپس یک نوع برگشتی هستند (برخلاف برخی از زبان‌های برنامه‌نویسی).
  • The last expression in a function body (or any block) becomes the return value. Simply omit the ; at the end of the expression. The return keyword can be used for early return, but the “bare value” form is idiomatic at the end of a function (refactor gcd to use a return).
  • برخی از توابع هیچ مقدار برگشتی ندارند و «نوع یکه» () را برمی‌گردانند. اگر -> () از بخش نوع برگشتی حذف شود، کامپایلر این را استنتاج خواهد کرد که هیچ نوع برگشتی وجود ندارد.
  • Overloading is not supported – each function has a single implementation.
    • Always takes a fixed number of parameters. Default arguments are not supported. Macros can be used to support variadic functions.
    • Always takes a single set of parameter types. These types can be generic, which will be covered later.