]> git.proxmox.com Git - rustc.git/blame - src/doc/reference/src/expressions/method-call-expr.md
New upstream version 1.23.0+dfsg1
[rustc.git] / src / doc / reference / src / expressions / method-call-expr.md
CommitLineData
ea8adc8c
XL
1# Method-call expressions
2
3A _method call_ consists of an expression followed by a single dot, an
4[identifier](identifiers.html), and a parenthesized expression-list. Method
5calls are resolved to methods on specific traits, either statically dispatching
6to a method if the exact `self`-type of the left-hand-side is known, or
7dynamically dispatching if the left-hand-side expression is an indirect [trait
8object](types.html#trait-objects). Method call expressions will automatically
9take a shared or mutable borrow of the receiver if needed.
10
11```rust
12let pi: Result<f32, _> = "3.14".parse();
13let log_pi = pi.unwrap_or(1.0).log(2.72);
14# assert!(1.14 < log_pi && log_pi < 1.15)
15```
16
17When resolving method calls on an expression of type `A`, Rust will use the
abe05a73
XL
18following order, only looking at methods that are
19[visible](visibility-and-privacy.html) and traits that are in scope:
ea8adc8c
XL
20
211. Inherent methods, with receiver of type `A`, `&A`, `&mut A`.
221. Trait methods with receiver of type `A`.
231. Trait methods with receiver of type `&A`.
241. Trait methods with receiver of type `&mut A`.
251. If it's possible, Rust will then repeat steps 1-5 with
26 `<A as std::ops::Deref>::Target`, and insert a dereference operator.
271. If `A` is now an [array](types.html#array-and-slice-types) type, then
28 repeat steps 1-4 with the corresponding slice type.
29
30Note: that in steps 1-4 the receiver is used, not the type of `Self` nor the
31type of `A`. For example
32
33```rust,ignore
34// `Self` is `&A`, receiver is `&A`.
35impl<'a> Trait for &'a A {
36 fn method(self) {}
37}
38// If `A` is `&B`, then `Self` is `B` and the receiver is `A`.
39impl B {
40 fn method(&self) {}
41}
42```
43
44Another note: this process does not use the mutability or lifetime of the
45receiver, or whether `unsafe` methods can currently be called to resolve
46methods. These constraints instead lead to compiler errors.
47
48If a step is reached where there is more than one possible method (where
49generic methods or traits are considered the same), then it is a compiler
50error. These cases require a [more specific
51syntax.](expressions/call-expr.html#disambiguating-function-calls) for method
52and function invocation.