https://doc.rust-lang.org/reference/expressions/method-call-expr.htmlA method call consists of an expression (the receiver) followed by a single dot, an expression path segment, and a parenthesized expression-list. Method calls are resolved to associated methods on specific traits, either statically dispatching to a method if the exact self-type of the left-hand-side is known, or dynamically dispatching if the left-hand-side expression is an indirect trait object.
let pi: Result<f32, _> = "3.14".parse();
let log_pi = pi.unwrap_or(1.0).log(2.72);
When looking up a method call, the receiver may be automatically dereferenced or borrowed in order to call a method. This requires a more complex lookup process than for other functions, since there may be a number of possible methods to call. The following procedure is used:
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.
For instance, if the receiver has type Box<[i32;2]>, then the candidate types will be Box<[i32;2]>, &Box<[i32;2]>, &mut Box<[i32;2]>, [i32; 2] (by dereferencing), &[i32; 2], &mut [i32; 2], [i32] (by unsized coercion), &[i32], and finally &mut [i32].
pub trait Clone {
fn clone(&self) -> Self;
}
方法去糖:
fn clone
(&T) -> T;
123i32.clone(): (&123).clone() 得到 123,这里按顺序发生的事情:
* 不存在 clone(i32) -> i32
* 对 i32 自动添加 &,得到 &i32;找到有 fn clone(&i32) -> i32,调用该方法
(&123).clone(): 存在 fn clone(&i32) -> i32,直接调用
(&mut 123).clone()
* 不存在 fn clone(&mut i32) -> i32
* &mut i32 的候选类型顺序:&mut i32, &&mut i32(自动添加 &), &mut &mut i32(自动添加 &mut), i32(解引用), &i32(解引用并自动添加 &)
* 对每个候选找方法定义,最终找到有 fn clone(&i32) -> i32,调用该方法
--
FROM 117.147.21.*