1

I am still learning Rust and my question is built upon Why does Rust have both call by value and call by reference? (but a bit different).

With a C/C++ background, I am confused how Rust allows the same method call on both value and its reference. I noticed in The Rust Programming Language book that the following code works fine:

let s1 = String::from("hello");
let length = s1.len();
let len = calculate_length(&s1);

fn calculate_length(s: &String) -> usize {
    s.len()
}

This means that the method call len() works on both the String value and its reference. I noticed the same thing happens to Vec<_> as well. In C/C++ one needs to dereference the pointer to be able to call its method (using operators like ->); otherwise, there would be a type mismatch. In Rust, does the compiler simply "dereference" the reference for you to call the method or is it because for classes like String and Vec, multiple methods are implemented under the hood for both the value (e.g., String) and the reference (e.g., &String and &str)?

Shepmaster
  • 274,917
  • 47
  • 731
  • 969
vanbastelaer
  • 129
  • 8
  • *In C/C++ one needs to dereference the pointer to be able to call its method (using operators like `->`); otherwise, there would be a type mismatch.* -- Note this isn't *quite* true; C pointers work this way, but C++ references do not, acting more like aliases, although they often compile to pointers behind the scenes. Rust references have properties of both; they generally act more like C pointers, but code that uses them can look a lot more like C++ code using references because of the syntax. – trentcl Mar 30 '20 at 16:06
  • Does [What are Rust's exact auto-dereferencing rules?](https://stackoverflow.com/questions/28519997/what-are-rusts-exact-auto-dereferencing-rules) answer your question, or is there more to it? – trentcl Mar 30 '20 at 16:06
  • @trentcl That question does answer mine! Thanks for the pointer! Just wondering, are you referring to C++'s polymorphism when you say "*C++ references do not, acting more like aliases, although they often compile to pointers behind the scenes*"? If not, can you elaborate a bit, if you don't mind? – vanbastelaer Mar 30 '20 at 16:23
  • Nothing to do with polymorphism; C++ references are not pointer-like because you don't have to use the `->` operator with them. For example, consider [these two functions](https://godbolt.org/z/jwwT_g), which compile to the same assembly even though one uses a pointer with `->` and the other uses a reference with `.` – trentcl Mar 30 '20 at 16:42

0 Answers0