Newbie Question on match and borrows


Rust beginner here, I was wondering why I needed a mutable reference to num_map on line 9, would num_map be moved into the match expression if I didn’t use a reference?

Also, for line 10, I’m not exactly sure why I needed the &mut for Some and None. Would really appreciate it if someone could offer a bit of guidance, thanks in advance!


If you remove all of the &muts, it compiles

I’m not sure why you put them in in the first place, so it’s hard to say!


Thanks for taking a look at my code! I think I put &mut num_map.get(i) first and then the compiler complained about the other ones having incompatible types, which is why I added &mut's all over the place.

The reason I put &mut in the num_map.get(i) call was because I thought it would be moved inside the match expression if I didn’t, looks like I was wrong!


If you look at the definition of HashMap::get() it borrows self, so you won’t move it into the match expression.

It also feels a little odd that just trying to print the statistics for a list of numbers will shuffle them around (the sort()) as a side-effect. But that’s not really related to ownership or borrows.


Fair point. I should make a copy of the vector and sort that instead, in order to extract the mean.