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
)?