函数

函数使用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);

}

}

¥ 我要打赏

纠错/补充

收藏

上一篇:

加QQ群啦,易百教程官方技术学习群

注意:建议每个人选自己的技术方向加群,同一个QQ最多限加 3 个群。

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐