有時,函數可能有相同的名字。就像下面這些代碼:
~~~
trait Foo {
fn f(&self);
}
trait Bar {
fn f(&self);
}
struct Baz;
impl Foo for Baz {
fn f(&self) { println!("Baz’s impl of Foo"); }
}
impl Bar for Baz {
fn f(&self) { println!("Baz’s impl of Bar"); }
}
let b = Baz;
~~~
如果我們嘗試調用`b.f()`,我們會得到一個錯誤:
~~~
error: multiple applicable methods in scope [E0034]
b.f();
^~~
note: candidate #1 is defined in an impl of the trait `main::Foo` for the type
`main::Baz`
fn f(&self) { println!("Baz’s impl of Foo"); }
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
note: candidate #2 is defined in an impl of the trait `main::Bar` for the type
`main::Baz`
fn f(&self) { println!("Baz’s impl of Bar"); }
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~
我們需要一個區分我們需要調用哪一函數的方法。這個功能叫做“通用函數調用語法”(universal function call syntax),這看起來像這樣:
~~~
Foo::f(&b);
Bar::f(&b);
~~~
讓我們拆開來看。
~~~
Foo::
Bar::
~~~
調用的這一半是兩個traits的類型:`Foo`和`Bar`。這樣實際上就區分了這兩者:Rust調用你使用的trait里面的方法。
~~~
f(&b)
~~~
當我們使用[方法語法](http://doc.rust-lang.org/nightly/book/method-syntax.html)調用像`b.f()`這樣的方法時,如果`f()`需要`&self`,Rust實際上會自動地把`b`借用為`&self`。而在這個例子中,Rust并不會這么做,所以我們需要顯式地傳遞一個`&b`。
## 尖括號形式(Angle-bracket Form)
我們剛才討論的通用函數調用語法的形式:
~~~
Trait::method(args);
~~~
上面的形式其實是一種縮寫。這是在一些情況下需要使用的擴展形式:
~~~
<Type as Trait>::method(args);
~~~
``中。在這個例子中,類型是`Type as Trait`,表示我們想要`method`的`Trait`版本被調用。在沒有二義時`as Trait`部分是可選的。尖括號也是一樣。因此上面的形式就是一種縮寫的形式。
這是一個使用較長形式的例子。
~~~
trait Foo {
fn clone(&self);
}
#[derive(Clone)]
struct Bar;
impl Foo for Bar {
fn clone(&self) {
println!("Making a clone of Bar");
<Bar as Clone>::clone(self);
}
}
~~~
這會調用`Clone`trait的`clone()`方法,而不是`Foo`的。
- 前言
- 1.介紹
- 2.準備
- 2.1.安裝Rust
- 2.2.Hello, world!
- 2.3.Hello, Cargo!
- 3.學習Rust
- 3.1.猜猜看
- 3.2.哲學家就餐問題
- 3.3.其它語言中的Rust
- 4.高效Rust
- 4.1.棧和堆
- 4.2.測試
- 4.3.條件編譯
- 4.4.文檔
- 4.5.迭代器
- 4.6.并發
- 4.7.錯誤處理
- 4.8.外部語言接口
- 4.9.Borrow 和 AsRef
- 4.10.發布途徑
- 5.語法和語義
- 5.1.變量綁定
- 5.2.函數
- 5.3.原生類型
- 5.4.注釋
- 5.5.If語句
- 5.6.for循環
- 5.7.while循環
- 5.8.所有權
- 5.9.引用和借用
- 5.10.生命周期
- 5.11.可變性
- 5.12.結構體
- 5.13.枚舉
- 5.14.匹配
- 5.15.模式
- 5.16.方法語法
- 5.17.Vectors
- 5.18.字符串
- 5.19.泛型
- 5.20.Traits
- 5.21.Drop
- 5.22.if let
- 5.23.trait對象
- 5.24.閉包
- 5.25.通用函數調用語法
- 5.26.包裝箱和模塊
- 5.27.`const`和`static`
- 5.28.屬性
- 5.29.`type`別名
- 5.30.類型轉換
- 5.31.關聯類型
- 5.32.不定長類型
- 5.33.運算符和重載
- 5.34.`Deref`強制多態
- 5.35.宏
- 5.36.裸指針
- 6.Rust開發版
- 6.1.編譯器插件
- 6.2.內聯匯編
- 6.3.不使用標準庫
- 6.4.固有功能
- 6.5.語言項
- 6.6.鏈接參數
- 6.7.基準測試
- 6.8.裝箱語法和模式
- 6.9.切片模式
- 6.10.關聯常量
- 7.詞匯表
- 8.學院派研究
- 勘誤