Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
Living with Rust Long-Term – Jon Gjengset (youtube.com)
33 points by jstx1 on March 4, 2023 | hide | past | favorite | 6 comments


error[E0382]: borrow of moved value

Uh-oh. Looks like you’ve run into the dreaded borrow checker!

Are there best practices and how to avoid common sense rust pitfalls!?


Well, don't move the value. Who is supposed to free it? If not what you're passing it to, use a reference, or use a container that owns the value.


Pretty sure they were being sarcastic.


Yeah I can see that now lol


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/




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: