函式
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. Thereturn
keyword can be used for early return, but the "bare value" form is idiomatic at the end of a function (refactorgcd
to use areturn
). - 某些函式沒有回傳值,會傳回
()
這個「單位型別」。如果省略-> ()
傳回型別,編譯器則會推斷出這點。 - Overloading is not supported -- each function has a single implementation.
- 請一律採用定量參數。系統不支援預設引數。如要支援可變參數函式,請使用巨集。
- Always takes a single set of parameter types. These types can be generic, which will be covered later.