Want to learn how to write more memory efficient code

66 points super_lambda_lord 20 comments

Hello. I'm an experienced dev but new ish to rust. I feel like I'm in a place with my rust skills that is likely pretty common. Ive been using it for a few months and have gotten comfortable with the language and syntax, and I no longer find myself fighting the compiler as much. Or at least most of the compile errors I get make sense and I can solve them.

Overall, my big issue is I find myself cloning too much. Or at least I think I am at least. Ive read that new rust devs should just clone and move on while trying to get a feel for the language, but obviously I want to increase my skills.

I'm basically looking for advice on how to minimize cloning. I'll list a few situations off the top of my head, but general advice is also great.

Thanks in advance.

PS. Dropping links is an acceptable form of help, I am capable of reading relevant articles.

  1. Better use of AsRef/Borrowed types. This I've been planning to Google documentation on, just wanted to put it on the list.

  2. Creating derived data structures. Ie, a struct that is populated with items from an existing struct and I don't want to transfer ownership, or creating new vectors/hashmaps/etc as intermediate values in a function. I end up cloning the data to do this.

  3. Strings. Omfg coming from Java strings in rust drive me mad. I find myself calling to_string() on am &str far too often, I have to be doing something wrong. And also, conveying OsString to String/star is just weird.

  4. Lifetimes. I understand them in principle, but I never know where the right place to use them is. Better use of lifetimes may be the solution to some of my other problems.

Anyway, that's a non-exhsustive list. I'm open to input. Thanks.