(introductory book chapt. 4.3) calling functions on references

Hello,

I am reading the Rust book and here The Slice Type - The Rust Programming Language
there is a line where a function is invocated on a reference variable.
fn first_word(s: &String) -> usize { let bytes = s.as_bytes(); ... }
If I make a compound datatype and pass its reference to a function can I just invoke the function on it analogously? It doesnt seem like a C pointer/reference where I need to dereference &s first. example:

fn compound_dt(compound_type: &CompoundType) -> CompoundType {
let var = compound_type.foo();...}

Ultimately, many methods expect a reference already, anyways. So if fn foo(&self, …) is what you have, then a value of type c: &Compound is arguably even more correct already as the operand in a c.foo() method call.

Method call syntax does have convenience capabilities of adding or removing a level of reference indirection as necessary. (The details of the precise mechanism of method resolution is documented but usually unimportant for beginners.)

Outside of methods, for usual function calls like bar(x), it does make a difference. If bar accepts &CompoundType then when you have c: CompoundType you call bar(&c) but for d: &CompoundType it's just bar(d).

(Though there's a different mechanism, implicit deref coercions, that would allow bar(&d) to compile, too.)

If you have a function baz(i: i32) and a reference r: &i32 then you have to write the call with the dereferencing operator, as baz(*i32) (in this case there's no compiler magic - however if you get it wrong, the error message should usually already suggest hot to change your code to make it work).

if you mean invoke an method, the answer is yes, if the method takes &self as it's first argument (called the "receiver" argument).

the relevant reference is the chapter "method call expression", to quote:

The first step is to build a list of candidate receiver types. Obtain these by repeatedly dereferencing the receiver expression's type, adding each type encountered to the list, then finally attempting an unsized coercion at the end, and adding the result type if that is successful. Then, for each candidate T, add &T and &mut T to the list immediately after T.

Blockquote (The details of the precise mechanism of method resolution is documented but usually unimportant for beginners.)

this link is not working but thanks both of you!

ah, my phone's autocorrect "fixed" the link, removing some hyphens :sweat_smile:

It's the same link that @nerditation also shared, anyway.