Skip to content

RS-OWNE0001 · clone_inside_loop

Count explicit copies made inside loops.

This is a deterministic rule for rust. Read its implementation.

Report each clone or to_owned written inside a for, while, or loop body. This is a measurement because syntax alone cannot distinguish a redundant copy from ownership transferred into one result per iteration. Projects may set a ceiling when repeated copies are unwanted.

This is the counterpart to the lifetime rules. Removing an annotation by owning the data is usually right, and this is the one place where it usually is not.

Each finding names the value copied, the function it sits in, the line, and how deeply nested the loop around it is. The repair is a choice, because hoisting the copy and borrowing across the loop are different edits and only the body says which one holds. The value is the number of copies made inside a loop.

A copy of something the loop then consumes, such as an owned value handed to a spawned task or pushed into a collection that outlives the iteration, is a copy that has to happen. A cheap copy of a small value is a copy the compiler often removes, and measuring is what settles it.

for item in items {
registry.insert(prefix.clone(), item);
}
let prefix = prefix.clone();
for item in items {
registry.insert(prefix.as_str(), item);
}