Continuing the discussion from Rust beginner notes & questions :
This post started out combining issues, so is kept as such. Main topic of this thread is issues 1 to 4 of the below post, preferably create and link new topic on each when replying.
A bit of background: I'm an experienced programmer who's worked in over 20 languages including some esoteric ones, and I finally sat down to learn Rust and bumped into what I'm sure are common issues.
Unusually, I'm struggling to find good solutions to these, which is a concern because typically picking up each new language has been easier than the last.
Issue #1: How do I access the iterator itself in a for loop? I.e.:
for x in vec.iter() {
...
// once we reach a certain po…
for (i, x) in v.iter().enumerate() {
if *x == 2 {
use_slice(&v[i..]);
}
}
x: &mut u8 is a constant pointer to a mutable u8; mut x: &u8 is a mutable pointer to a constant u8. mut x: &mut u8 is mutable for both.
There’s nothing super easy for this right now. You can put the common fields into a struct and then embed that struct in the enum variants.
Thank you for the feedback, but for the iterator case I may not have explained what I meant well enough. I'm aware of enumerate(), but that that returns an index, not the iterator.
What I would like is for an ergonomic way to access both the 'iterated value' and the 'iterator' at the same time without having to manually desugar the for loop.
For the iterator use
while let Some(i) = iter.next() {}
The for loop is a syntax sugar for simple cases, and it consumes the iterator (calls into_iter()).
References around closures/iterators/auto-deref can be tricky. It takes a bit of experience to know iter() is by reference and iter().cloned() and into_iter() are the alternatives.
Rust doesn't have a concept of immutable memory. All memory can be mutable in principle (that's why you can always make owned objects mutable). Only references and variable bindings have mutability attached, and temporary immutability of memory is enforced by restricting where and when these references can exist.
The closest type would be &mut &T, but I don't recall such thing being used in practice. Maybe let mut x: &T is the thing you need?