Dev Notes

Software Development Resources by David Egan.

Passing by Reference in Rust


Rust
David Egan

Example of passing arguments by reference in Rust:

fn main() {
  // Define a mutable variable and a reference to it
  let mut n_main: usize = 100;
  let n_main_ref: &usize = &n_main;

  // Prints the return value of `increment_value`, original variable unchanged
  println!("{}", increment_value(n_main_ref)); // "101"
  println!("n_main = {}", n_main); // "n_main = 100"

  // This function receives a mutable reference, and changes the original value.
  amend(&mut n_main);
  println!("n_main = {}", n_main); // "n_main = 199"
}

// Accepts a mutable reference, changes the value it refers to, no return value
fn amend(n_inc_ref: &mut usize) {
    *n_inc_ref +=99;
}

// Accepts a reference, does not mutate it, returns same type as the passed-in reference
fn increment_value(n_inc_ref: &usize) -> usize {
  n_inc_ref + 1
}

comments powered by Disqus