Quick Advice to New Rustaceans

submited by
Style Pass
2025-01-12 15:30:08

Let’s say you’re new to Rust. Maybe you’ve read TRPL and worked through Rustlings or YARR. You can write enough Rust to solve problems, and can fix compiler errors when they crop up. Now you come to a more nebulous question: how do you write good Rust? And how do you write Rust that won’t require mortal combat with the borrow checker?

Because Rust makes cloning explicit, I get the feeling that a lot of newcomers find it stressful. How expensive of an operation is a .clone()? Unfortunately, the answer can range from “very expensive” to “very cheap.” Reference-counted structures like an Arc or a channel can be cloned very cheaply. Generally strings like usernames, filenames, or paths are small, and therefore cheap. In these cases clone first and think later.

In cases where you’re uncertain, I would still strongly recommend cloning! You can always profile your code to see if the clones are performance drags, but I promise you it’s unlikely. In most cases choosing more suitable data structures, adding caches, or improving memory locality will all pay bigger dividends than agonizingly avoiding allocation.

Leave a Comment