18

I'm going through the interactive version of The Book, and I'm confused by the results of an exercise in Ch 4.3 - Fixing Ownership Errors.

The following code does not work, and they say it's because it would result in the same heap space being deallocated twice:

fn main() {
    let s = String::from("Hello world");
    let s_ref = &s; // reference s
    let s2 = *s_ref; // dereference s_ref
    println!("{s2}");
}

But in my mind, this should be equivalent to the following compilable code, which transfers ownership of s to s2 :

fn main() {
    let s = String::from("Hello world");
    let s_ref = &s; // reference s
    let s2 = s; // move s directly
    println!("{s2}");
}

If s_ref is a reference to s, then dereferencing s_ref should return the String s, shouldn't it? Why can't s be moved to s2 with either the above code or let s2 = *&s;, which fails in the same way?

you are viewing a single comment's thread
view the rest of the comments
[-] b_van_b@programming.dev 1 points 1 year ago

Thanks for the detailed explanation! I guess the main takeaway is that a reference can never be converted back into an owned value. Later content in the book also gave more information about when you have the right to transfer ownership.

this post was submitted on 01 Jul 2023
18 points (100.0% liked)

Rust

5876 readers
113 users here now

Welcome to the Rust community! This is a place to discuss about the Rust programming language.

Wormhole

!performance@programming.dev

Credits

  • The icon is a modified version of the official rust logo (changing the colors to a gradient and black background)

founded 1 year ago
MODERATORS