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