0

I'm having trouble figuring out what's happening when I forward a reference argument to another function in Rust that also expects a reference argument.

Basically, I'm confused about when a value is a reference (that needs to be de-referenced with *) and when it's just a value that can be used directly. For example,

fn second(s: &String) {
    println!("Got string '{}'", *s);  // Can also use s 
}

fn first(s: &String) {
    second(s);                        // Can also use &s
}

fn main() {
    let s = String::from("Hello, World!");
    first(&s);
}

As shown above, any of the four total combinations of passing s from first into second and printing s inside second works. My intuition says that s inside first is a reference and thus &s would be a double reference, and that s inside second is a reference that needs to be de-referenced, but it doesn't seem to actually matter. What's going on here?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
AUD_FOR_IUV
  • 473
  • 1
  • 3
  • 16

0 Answers0