fasterthanlime / feedback

An issue tracker for articles/series/videos at https://fasterthanli.me/
13 stars 0 forks source link

A half-hour to learn Rust #277

Closed Utilitycoder closed 1 year ago

Utilitycoder commented 1 year ago

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:

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
        // `x` stops existing
    }
    // `x` no longer exists
}

Apparently, x_ref doesn't stop existing where it says so in the post, as the blow snippets:

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
        let y = x_ref;
        println!("{}", y);
        // `x` stops existing
        println!("{}", x);
    }
    // `x` no longer exists
}

evaluate to this:

x_ref = 42
42
42
fasterthanlime commented 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.