Earlier, I got told that I should generally use &Option<T> rather than Option<&T>. Does that also apply when use mut? That is, should I use &mut Option<T> rather than Option<&mut T>?
Thanks.
Joel
It depends.
&mut Option<T> lets you swap the value to/from None, whereas Option<&mut T> does not.
Analogous to how an argument might be &mut Vec<T> if you need to change the number of elements, but &mut [T] is better if you don't need to.
I'd argute that it's exactly the opposite.
Id does allow this, because it's an owned value. You can use Option::replace() on the owned option as well.
You got it wrong. What you were told is exactly the opposite.
Yep. Sorry. I remembered it backwards. Maybe this time it will stick in my head.
And for the case I am trying to do, Option<&mut T> will do what I want based on this and other discussions.
Thanks all,
Joel
No worries. By the way, try to use clippy more often in your projects, it will teach you idiomatic patterns like this one and that will certainly help you to learn more of them.
Yes, Clippy is very helpful. I ran it repeatedly on this first project, and at the end it reported no problems. This question came up in the second project, which is still too early to run clippy, as I have a bad havit of trying to capture too much of my design before I get things through clean compile. Working to break myself of that habit.
Yours,
Joel
I find it pretty handy as a editor plugin that saves me going too far with something dumb without actually blocking me.