I've recently come across Ben Hoyt's post comparing counting words in different programming languages. Since text processing is what I'm most familiar with and what I hope to start using Rust more for in the near future, I decided to spend some time with the various Rust solutions kindly provided by none other than Andrew Gallant (learn from the best, right?).
Along the way, I wasn't exactly sure why
Cell is needed in this function and why switching to a mutable ref leads to E0499 ("cannot borrow as mutable more than once at a time"). I understood why
Cell helps with the issue, but I was hazy on the exact mechanism that causes it.
Hoping that getting to the bottom of it would help me better understand borrowing and lifetimes, I originally wanted to post about this under the
help tag. But having spent a few evenings on it (and (re)learnt about reborrowing and a bunch of other things), I think I've figured out some answers. So I cleaned up my code experiments, added some explanatory prose for future me (who'll inevitably forget all of this) and I'm submitting it instead under
code review, as I would sincerely appreciate any feedback/comments on:
- the (in)correctness and phrasing of my explanations (maybe some of them are correct in spirit, but phrased in a way that uses terms too informally -- I remember using "blanket impl" wrong in the past, that sort of thing)
- the idiomaticity and performance characteristics of the three listed ways to avoid E0499 in this context (and possibly any other ways that come to mind)