Need explain about rust dangling references?

fn no_dangle(ref_s: &String) -> &String {
    ref_s
}
fn main() {
    let s = String::from("hello");
    let reference_to_s = no_dangle(&s);
    println!("{reference_to_s}");
}

Hi everyone, I'm new to Rust and still learning about references. AFAIK, in no_dangle function, a reference (input) is passed then when calling function, no_dangle will take ownership and pass a reference (output) through reference_to_s. I have 3 questions in here.

  1. Rust automatically drops object if it goes out of scope so why the ref_s is dropped but the code is still compiled without error?
  2. The reference (input) and the reference (output) is the same or not? I think they're difference because ref_s when out of scope is dropped then they should be difference so the code can compile
  3. Can you explain the process of passing a reference until it's dropped?

No, that's the whole point of taking a reference.

No, they are the same (they point to the same place).

4 Likes

Here's the relevant chapter of the book.

https://doc.rust-lang.org/stable/book/ch04-02-references-and-borrowing.html

References don't affect ownership, by design. &String isn't just a string passed "by reference". It's a String temporarily loaned out, while the original s is frozen for the duration of the loan and can't be moved or destroyed.

One important thing to note is that references do not affect lifetime of objects they borrow from. It's the other way around - ownership and scopes dictate how long objects live, and loans are allowed to exist only while the source object would be alive anyway.

1 Like

There's two relevant answers here. First, immutable references are one of the types in Rust marked with the Copy trait, which means that they can be duplicated implicitly and dropping them is a no-op. Second, more generally, even for types that don't support Copy, rust does not drop all variables at the end of scope. Otherwise you could never return values, or pass them by-value. Instead, Rust drops initialized values at the end of their scope, and values can become de-initialized (also called “moved out of”) if you return them or pass them to something else by-value.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.