i am new to rust so i may be confused or ignorant but i couldn’t find an ansower for my situation or faild in my search at least
so this is my code
fn main() {
let sorted_array: [i32; 10] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let target: i32 = 3;
let mut left: usize = 0;
let mut right: usize = 10;
while left <= right {
let middle: usize = (left + right) / 2;
if sorted_array[middle] == target {
println!("Target index {middle}");
break;
}
if sorted_array[middle] > target {
right = middle - 1;
break;
}
if sorted_array[middle] < target {
left = middle + 1;
break;
}
}
}
so i get this error
warning: value assigned to `right` is never read
--> src/main.rs:13:13
|
13 | right = middle - 1;
| ^^^^^
|
= help: maybe it is overwritten before being read?
= note: `#[warn(unused_assignments)]` on by default
but i am using these variables at
let middle: usize = (left + right) / 2;
doesn’t it count as a read? if not what is counted as a read? and how can i wright this code correctly?
i am still tring to learn so i will be thankful for an answer
i tried to find the same mistake but all the question had a work around or the compiler had a right to complain
i expect any source that answer my question or a direct answer to my questions from the community
sorry for any english mistakes
>Solution :
I’m guessing you don’t want the break in the second and third if statement. The compiler is pointing out that you assign a value to right, then the loop is immediately exited, thus the value is never read again.