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" ]