Newbie Question on match and borrows


#1

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?

https://play.rust-lang.org/?gist=da726ddb0e3ad5a39fd0d82eea33f394&version=stable

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!


#2

If you remove all of the &muts, it compiles https://play.rust-lang.org/?gist=c1b73831e8fa1bb14b591961c4d13183&version=stable

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


#3

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!


#4

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.


#5

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