RUST Documentation 따라 공부하기 7


References and Borrowing

fn main() {
  let s1 = String::from("hello");
  let len = calculate_length(&s1); // rather than returning tuple (String, usize);
  println!("The length of '{}' is {}.", s1, len);

fn calculate_length(s: $String) -> usize {
} // s goes out of scope. But because it does not have ownership of what it refers to, nothing happens.

Passing references : allows to refer to some value without taking ownership of it.

  • opposite of referencing : deferencing with operetor *

  • If we try to modify something that we've borrowed, it doesn't work!

    Just as variables are immutable by default, so are references.

Mutable References

fn main() {
  let mut s = String::from("hello");
  change(&mut s);

fn change(some_string: &mut String) P
some_string.push_str(", world");

Only one mutable reference to a particular piece of data in a particular scope.

  • Benifit of having this restriction : Rust can prevent data races at compile time.

    • when data races occur:
      • Two or more pointers access the same data at the same time
      • At least one of the pointers is being used to write to the data
      • There's no mechanism being used to synchronize access to the data.
  • Also, we cannot have a mutable reference while we have an immutable one.

  • But, multiple immutable references are okay.

let mut s = String::from("hello");

let r1 = &s; // no problem
let r2 = &s; // no problem
println!("{} {}", r1, r2);
// r1 and r2 are no longer used after this point

let r3 = &mut s; // it is no problem..!
println!("{}", r3);

Dangling References

A pointer that references a location in memory that may have been given to someone else, by freeing some memory while preserving a pointer to that memory.

In Rust, the compiler guarantees that references will never be dangling references...!

// try to make dangling references
fn main() {
  let reference_to_nothing = dangle();

fn dangle() -> &String {
  let s = String::from("hello");
} // s goes out of scope and is dropped -> memory goes away
  • Compiler occurs error : missing lifetime (Chapter 10) specifier.

References must always be valid!