6.flow_and_control 流程控制

This commit is contained in:
shikong 2024-06-01 19:18:14 +08:00
parent d5b4ca2cb8
commit 6509f62182
Signed by: Shikong
GPG Key ID: BD85FF18B373C341
4 changed files with 47 additions and 1 deletions

View File

@ -6,9 +6,13 @@
<sourceFolder url="file://$MODULE_DIR$/2.hello_cargo/src" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/2.hello_cargo/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/3.guessing_game/src" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/3.guessing_game/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/4.variables/src" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/4.variables/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/5.function/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/6.flow_and_control/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/x.bubble_sort/src" isTestSource="false" />
<excludeFolder url="file://$MODULE_DIR$/2.hello_cargo/target" /> <excludeFolder url="file://$MODULE_DIR$/2.hello_cargo/target" />
<excludeFolder url="file://$MODULE_DIR$/3.guessing_game/target" /> <excludeFolder url="file://$MODULE_DIR$/3.guessing_game/target" />
<excludeFolder url="file://$MODULE_DIR$/4.variables/target" /> <excludeFolder url="file://$MODULE_DIR$/4.variables/target" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content> </content>
<orderEntry type="inheritedJdk" /> <orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" /> <orderEntry type="sourceFolder" forTests="false" />

View File

@ -0,0 +1,8 @@
[package]
name = "flow_and_control"
edition = "2021"
version.workspace = true
[dependencies]
# https://crates.io/search?q=rand
rand = "0.8.4"

View File

@ -0,0 +1,34 @@
use std::ops::Range;
use rand::Rng;
fn gen_rand_num(rng:Range<i32>) -> impl Fn() -> i32 {
let self_rng = rng.clone();
// 使用 move 将变量的所有权转移到闭包中
move || -> i32 {
rand_num(self_rng.clone())
}
}
fn rand_num(rng:Range<i32>) -> i32 {
rand::thread_rng().gen_range(rng)
}
fn main() {
// 生成一个闭包,该闭包每次调用时返回一个 -100 到 100 之间的随机数
let fn_rand_num = gen_rand_num(-100..100);
// 调用闭包,获取随机数
let mut num:i32 = fn_rand_num();
let max_num = rand::thread_rng().gen_range(0..10);
let min_num = rand::thread_rng().gen_range(-10..0);
println!("当随机生成的数 >= {} 且 <= {} 时结束", min_num,max_num);
while num < min_num || num > max_num {
println!("随机数为: {}", num);
num = fn_rand_num();
}
println!("当随机生成的数 >={} 且 <= {}时结束", min_num,max_num);
println!("最终的随机数为: {}", num);
}

View File

@ -17,7 +17,7 @@ members = [
"2.hello_cargo", "2.hello_cargo",
"3.guessing_game", "3.guessing_game",
"4.variables", "4.variables",
"5.function", "5.function", "6.flow_and_control",
"x.bubble_sort" "x.bubble_sort"
] ]