From 6509f62182ec78e884d5a456cd4646dcf338ba36 Mon Sep 17 00:00:00 2001 From: shikong <919411476@qq.com> Date: Sat, 1 Jun 2024 19:18:14 +0800 Subject: [PATCH] =?UTF-8?q?6.flow=5Fand=5Fcontrol=20=E6=B5=81=E7=A8=8B?= =?UTF-8?q?=E6=8E=A7=E5=88=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .idea/rust_study.iml | 4 ++++ 6.flow_and_control/Cargo.toml | 8 ++++++++ 6.flow_and_control/src/main.rs | 34 ++++++++++++++++++++++++++++++++++ Cargo.toml | 2 +- 4 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 6.flow_and_control/Cargo.toml create mode 100644 6.flow_and_control/src/main.rs diff --git a/.idea/rust_study.iml b/.idea/rust_study.iml index 91e2829..a5bf69f 100644 --- a/.idea/rust_study.iml +++ b/.idea/rust_study.iml @@ -6,9 +6,13 @@ + + + + diff --git a/6.flow_and_control/Cargo.toml b/6.flow_and_control/Cargo.toml new file mode 100644 index 0000000..b1f4777 --- /dev/null +++ b/6.flow_and_control/Cargo.toml @@ -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" diff --git a/6.flow_and_control/src/main.rs b/6.flow_and_control/src/main.rs new file mode 100644 index 0000000..01786e7 --- /dev/null +++ b/6.flow_and_control/src/main.rs @@ -0,0 +1,34 @@ +use std::ops::Range; + +use rand::Rng; + +fn gen_rand_num(rng:Range) -> impl Fn() -> i32 { + let self_rng = rng.clone(); + // 使用 move 将变量的所有权转移到闭包中 + move || -> i32 { + rand_num(self_rng.clone()) + } +} + +fn rand_num(rng:Range) -> 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); +} diff --git a/Cargo.toml b/Cargo.toml index f7e3df1..48bd041 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,7 +17,7 @@ members = [ "2.hello_cargo", "3.guessing_game", "4.variables", - "5.function", + "5.function", "6.flow_and_control", "x.bubble_sort" ]