Hacker News new | ask | show | jobs
by winrid 1209 days ago
Yeah I can see that now lol
1 comments

No seriously are there best practices to avoid common rust pitfalls with the borrow checker?
The answer to that question depends really on the context.

At the end of the day the borrow checker is there to help you. If a function takes ownership of a value, like a string, it generally means that it wants exclusive access to the memory and may want to mutate it.

If you are writing a function that doesn’t really need ownership of a value, then make sure you accept references rather than take ownership.

There are cases where ownership rules make it hard to do something you really want to do. One example I run into is using “itertools.group_by_key” - this needs an owner reference, which means I often clone the value.

This isn’t optimal but often this is fine. If the code you are writing isn’t in the hot path, then it’s usually OK to just clone values without much thought.

Basically, if you are new to Rust then try passing a reference via &obj, and if that doesn’t work then try obj.clone(). Is it perfect? No. Is it good? Probably not. Is it good enough to get you moving forward? In most cases yes.

I wrote about this here: https://tomforb.es/i-hope-i-hate-this-code-one-day/