Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

A very specific case on admittedly a toy project.

I was working on a card game simulator and I had a Vec of players. I needed to pull two players from that Vec and the first player would give a card to the second player. In my head I would grab both players via get_mut and then perform my operation. However, get_mut borrows the vec mutable and the compiler complained that I borrowed the Vec mutably two times.

It took me a bit to understand why the compiler complained, but then it clicked: It couldn't prove that get_mut wasn't returning the same item both times.

There were a few solutions. One was to borrow the first player, take a card, drop the &mut and then take the second player. At some point in the future I could use https://github.com/rust-lang/rust/issues/104642 to get_many_mut. I ended up with a pretty inefficient version of get_many_mut that fully traversed my iterator to get the two mut references (which works because traversing the iterator guarantees you won't see the same element twice) and it was fine for a collection of a half dozen players.

Anyway, there's a little example.

Anyway, it was a small thing but



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: