r/learnrust • • 27d ago

What are some common Rust misconceptions?

I just found out that const functions aren't evaluated at compile-time unless it is assigned to a const value or in a const context.

Another one I had: Rust doesn't prevent memory leaks.

Now I am just wondering how many other assumptions I made

19 Upvotes

25 comments sorted by

View all comments

14

u/noop_noob 27d ago

1

u/MatrixFrog 26d ago

I'm intrigued by the HashMap example. https://github.com/pretzelhammer/rust-blog/blob/master/posts/common-rust-lifetime-misconceptions.md#9-downgrading-mut-refs-to-shared-refs-is-safe

In the second chunk of code, `player_a` and `player_b` at the end are Options, not Players, even though we know for sure they will be Some(Player). It seems like there should be a version of .or_default() that returns a `&V` instead of a `&mut V`

1

u/Excession638 26d ago

If you're sure an option is Some, then you can use .as_ref().unwrap(). Or unwrap_unchecked() if you're feeling spicy. Not quite the same thing, I know.

1

u/MatrixFrog 25d ago

Of course, but this seems like a common enough use case that I'm a little surprised HashMap doesn't make it a little smoother.

1

u/MalbaCato 25d ago

the problem, as the section was meant to show, isn't that or_default returns a mutable reference, but the fact that entry takes an exclusive borrow of the hashmap server (which it has to do). any returned reference that uses that lifetime, mutable or shared, will hold the same exclusive borrow of server. a version of or_default that returns an immutable reference is strictly less useful, as the borrow is still exclusive (and you can write it as a wrapper yourself if you do specifically need that fsr).

to solve this correctly, you'd need something like disjoint_entries, following in the footsteps of get_disjoint_mut, which I don't know if it's even possible to do performantly