rust-unofficial / patterns

A catalogue of Rust design patterns, anti-patterns and idioms
https://rust-unofficial.github.io/patterns/
Mozilla Public License 2.0
7.85k stars 354 forks source link

example in the section 'Clone to stasify borrow checker' may deprecated due to NLL #290

Closed mokurin000 closed 2 years ago

mokurin000 commented 2 years ago
// define any variable
let mut x = 5;
// Borrow `x` -- but clone it first
let y = &mut (x.clone());
// perform some action on the borrow to prevent rust from optimizing this
//out of existence
*y += 1;
// without the x.clone() two lines prior, this line would fail on compile as
// x has been borrowed
// thanks to x.clone(), x was never borrowed, and this line will run.
println!("{}", x);

the println! could work due to NLL even if there is no clone() call, to solve this, *y += 1; should be placed under println!, so at the println line, y lives

pickfire commented 2 years ago

Deperated?

mokurin000 commented 2 years ago

Deperated

Sorry , I mean, deprecated

sollyucko commented 2 years ago

Wouldn't the behavior be different, printing 5 with clone and 6 without?

mokurin000 commented 2 years ago

Wouldn't the behavior be different, printing 5 with clone and 6 without?

behavior will not change, so actually only this line will run. needs change

image image