Rust函數

函數

函數使用fn關鍵字聲明。 其參數的數據類型註解,就像變量,並且如果該函數返回一個值,返回類型必須箭頭後指定 ->.

在函數的最終表達式將被用作返回值。或者, return語句可用於早期從函數內返回一個值,即使從內循環或 if 語句

讓我們改寫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: u32, rhs: u32) -> 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: u32) -> () {
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: u32) {
for n in 1..n + 1 {
fizzbuzz(n);
}
}