函数
1. fn gcd(a: u32, b: u32) -> u32 {
2. if b > 0 {
3. gcd(b, a % b)
4. } else {
5. a
6. }
7. }
9. fn main() {
10. println!("gcd: {}", gcd(143, 52));
11. }
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. Thereturnkeyword can be used for early return, but the “bare value” form is idiomatic at the end of a function (refactorgcdto use areturn). - 有些函数没有返回值,会返回“单元类型(unit type)”
()。如果省略了-> ()的返回类型,编译器将会自动推断。 - 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.
