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

Why does an iterator variable need to be mutable

I am a newcomer to the rust scene. Still learning the in n outs of ownership, borrowing, lifetimes etc. Been working with NodeJS my whole career.

use battery::Manager;
use spin_sleep::sleep;
use std::time::Duration;
fn main() {
    loop {
        if let Ok(manager) = Manager::new() {
            if let Ok(batteries) = manager.batteries() {
//                    ^^^^^^^^^ - This variable
//Rust analyzer tells me to make it mutable and it is fixed when I do so
                if let Some(Ok(battery)) = batteries.next() {
                    println!("Vendor: {:?}", battery.vendor());
                    println!("Model: {:?}", battery.model());
                    println!("State: {:?}", battery.state());
                    println!("Charge: {:?}", battery.state_of_charge());
                    println!("Time to full charge: {:?}", battery.time_to_full());
                    println!("");
                }
            }
        }
        sleep(Duration::from_secs(180));
    }
}

>Solution :

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

Every time you call batteries.next(), you get a different values (or None when it’s finished).

This is because the iterator has an internal state, which can for example be an index in a referenced collection.

Calling next changes this internal state, which means the iterator has to be muted.

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