Shadowing in a loop
โ Rust ๐ 2025-11-30 ๐ค surdeus ๐๏ธ 3I made some modifications to the guessing game from the Rust book and attempted to use binary search to give the player a hint about where the correct answer might be. In my first approach, I created three immutable variablesโstart, end, and hint. My intention was for the binary search function to return updated values for these three variables in each iteration, which I would then reassign to the original variables using shadowing.
However, I noticed that after the first iteration, the values stopped updating. I eventually resolved the issue by making the variables mutable when initializing them and updating them directly within the binary search function instead of reassigning them.
I want to understand why my initial version, which used immutable variables and shadowing, did not work as expected.
use std::{cmp::Ordering, io};
use rand::Rng;
fn bisect(num: &i32, start: i32, end: i32) -> (i32, i32, String){
let mid = (start + end) / 2;
match mid.cmp(num){
Ordering::Equal => return (start, mid, String::from(format!("Try Again: The correct answer is between {start} and {mid}"))),
Ordering::Greater => return (start, mid, String::from(format!("Try Again: The correct answer is between {start} and {mid}"))),
Ordering::Less => return (mid, end, String::from(format!("Try Again: The correct answer is between {mid} and {end}")))
}
}
fn main() {
// use this
let (mut start, mut end, mut hint) = (1, 100, String::from("Enter a number between zero and hundred"));
/*
this won't work
let (start, end, hint) = (1, 100, String::from("Enter a number between zero and hundred"));
*/
println!("Welcome to guess the number: {hint}");
let secret_number: i32 = rand::rng().random_range(start..=end);
loop{
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to readline");
let guess: i32 = match guess.trim().parse(){
Ok(num) => num,
Err(_) => continue
};
// use this
(start, end, hint) = bisect(&secret_number, start, end);
/*
this won't work
let (start, end, hint) = bisect(&secret_number, start, end);
*/
match guess.cmp(&secret_number){
Ordering::Equal => {println!("{guess} is the correct answer"); break},
Ordering::Greater => println!("{hint}"),
Ordering::Less => println!("{hint}"),
}
if (end - start) <= 1{
println!("Game Over! You couldn't take the hint");
break;
}
}
}
Summary (click for more details)
2 posts - 2 participants
๐ท๏ธ Rust_feed