tomas
tomas

Reputation: 23

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));
    }
}

Upvotes: 2

Views: 196

Answers (1)

Denys Séguret
Denys Séguret

Reputation: 382434

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.

Upvotes: 7

Related Questions