2

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

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Ok, so batteries is an iterator and since iterator changes its state, it has to be mutable, but the value it gives is not mutable since it is a reference right?
The signature of the next method is: fn next(&mut self) -> Option<Self::Item>. It requires &mut self, but you are giving it &self. Specifying the batteries variable as mutable with mut batteries will give you the type of reference that the next method requires.
@tomas This isn't about the values returned by the iterator (which could be mutable references with an IterMut) but about the iterator. manager.batteries() returns an iterator and this iterator has to be mutable to call next().

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.