Closed Utilitycoder closed 1 year ago
I don't understand what you're trying to say.
The second code snippet is a different code snippet, but it's essentially just this:
fn main() {
// `x` doesn't exist yet
{
let x = 42; // `x` starts existing
let x_ref = &x; // `x_ref` starts existing - it borrows `x`
println!("x_ref = {}", x_ref);
// `x_ref` stops existing
println!("x = {}", x);
// `x` stops existing
}
// `x` no longer exists
}
Note that x_ref
is of type &T
and that's Copy
, so you can create as many copies of it as you want:
fn main() {
let x = 42;
let x_ref = &x;
println!("x_ref = {}", x_ref);
let (a, b, c) = (x_ref, x_ref, x_ref);
println!("(a, b,c) = {:?}", (a, b, c));
}
When you do let y = x_ref
, you're creating another reference to x
, and the original one (x_ref
) indeed stops existing, but that doesn't mean x
stops being borrowed. Hope that helps.
I found something wrong on this page:
https://fasterthanli.me/articles/a-half-hour-to-learn-rust#position=49.6
Here's what it is:
Apparently, x_ref doesn't stop existing where it says so in the post, as the blow snippets:
evaluate to this: