函数与控制流
函数 Functions
Section titled “函数 Functions”函数有 4 个基本组件:名称、参数、返回类型、函数体
函数体中的语句与表达式
- 函数体由一系列语句组成,可选的由一个表达式结束。
- 表达式会计算产生一个值。
- 语句没有返回值。
// 这是一个语句:执行某些操作的指令,不返回值fn main() { // 这是一个语句 let a = 6;
// {}是一个表达式:计算并返回一个结果值 let b = { let x = 1; x + 3 };
println!("{}", b) // 4
() // 隐式返回}fn main() { another_function(2, 3);}
// 必须声明每个参数的类型(参数名:类型)fn another_function(x: i32, y: i32) { println!("{} {}", x, y); // 2 3}- 返回值就是函数体里面最后一个表达式的值。
- 若要提前返回,需使用
return关键字,并指定一个值。
fn main() { let x = five();
println!("{}", x) // 5}
// 使用"->"声明函数返回值的类型// five()返回值的类型是i32,返回值是5fn five() -> i32 { 5}IF 表达式
Section titled “IF 表达式”fn main() { let n = 6;
if n % 4 == 0 { println!("n is divisible by 4") } else if n % 3 == 0 { println!("n is divisible by 3") // n is divisible by 3 } else if n % 2 == 0 { println!("n is divisible by 2") } else { println!("n is not divisible by 4,3,2") }}- break : 停止 loop
- continue : 跳出本次循环
代码示例:
fn main() { let mut counter = 0;
let result = loop { counter += 1;
if counter == 10 { break counter * 2; } };
println!("{}", result) // 20}loop 标签:
fn main() { let mut count = 0; // 给当前循环添加标签 'counting_up: loop { println!("count = {}", count); let mut remaining = 10;
loop { println!("remaining = {}", remaining); if remaining == 9 { break; }
if count == 2 { // 停止counting_up循环 break 'counting_up; }
remaining -= 1; }
count += 1; }
println!("End count = {}", count); // 2}fn main() { let mut n = 3;
while n != 0 { println!("{}", n); // 3 2 1 end n -= 1; }
println!("end")}
for...in循环遍历集合的元素
fn main() { let a = [10, 20, 30, 40, 50];
for element in a.iter() { println!("{}", element) // 10 20 30 40 50 }}
range可用于让for循环执行特定次数
fn main() { // (1..4) 会生成[1,2,3) for n in (1..4).rev() { println!("{}", n) // 3 2 1 }}