Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

value assigned to `right` is never read

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading