通过例子学习Rust

11 函数

fn关键字用于定义函数。函数的参数需要指定类型。如果函数有返回值,必须在->后面写明返回值类型。

函数体的最后一个表达式将被作为函数的返回值。或者,使用return语句提前返回一个值,即使在循环内也可以。

让我们用函数重写fizzbuzz。

// Unlike C/C++, there's no restriction on the order of function definitions fn main() { // We can use this function here, and define it somewhere later fizzbuzz_to(100); } // Function that returns a boolean value fn is_divisible_by(lhs: uint, rhs: uint) -> bool { // Corner case, early return if rhs == 0 { return false; } // This is an expression, the `return` keyword is not necessary here lhs % rhs == 0 } // Functions that "don't" return a value, actually return the unit type `()` fn fizzbuzz(n: uint) -> () { if is_divisible_by(n, 15) { println!("fizzbuzz"); } else if is_divisible_by(n, 3) { println!("fizz"); } else if is_divisible_by(n, 5) { println!("buzz"); } else { println!("{}", n); } } // When a function returns `()`, the return type can be omitted from the // signature fn fizzbuzz_to(n: uint) { for n in range(1, n + 1) { fizzbuzz(n); } }