这个问题在这里已有答案:
哪条规则使以下代码有效?
struct Dummy(i32);
impl Dummy {
pub fn borrow(&self) {
println!("{}", self.0);
}
}
fn main() {
let d = Dummy(1);
(&d).borrow();
d.borrow();
}
我希望d.borrow()
无法正常工作,因为它传递的self
与方法签名borrow(&self)
不匹配。
来自reference:
方法调用由表达式(接收者)后跟单个点,表达式路径段和带括号的表达式列表组成
在查找方法调用时,可以自动解除引用或借用接收器以调用方法。
自动解除引用或借用仅对接收方有效。如果没有表达式作为接收器它将无法工作。编译器会期望借用的类型。
例:
fn main() {
let d = Dummy(1);
let borrowed = Dummy::borrow(d);
}
编译器将显示错误:
error[E0308]: mismatched types
--> src/main.rs:12:34
|
12 | let borrowed = Dummy::borrow(d);
| ^
| |
| expected &Dummy, found struct `Dummy`
| help: consider borrowing here: `&d`
|
= note: expected type `&Dummy`
found type `Dummy`