2017-05-29 59 views
4

我想FnMut(&[f32]) -> f32工作, 不復制/粘貼完整的簽名,我想介紹某種別名,但有什麼方法可以創建特定FnMut的別名?

type Boo = FnMut(&[f32]) -> f32; 

fn f<F: Boo>(mut f: F) {} 

導致一個編譯器錯誤:

error[E0404]: expected trait, found type alias `Boo` 
--> src/main.rs:3:13 
    | 
3 |  fn f<F: Boo>(mut f: F) {} 
    |    ^^^ type aliases cannot be used for traits 

然後我試着:

trait Boo: FnMut(&[f32]) -> f32 {} 

fn f<F: Boo>(mut f: F) {} 

它編譯,但是如果我嘗試在另一個地方使用Boo到位性狀:

trait Boo: FnMut(&[f32]) -> f32 {} 

struct X(Vec<Box<Boo>>); 

我得到:

error[E0191]: the value of the associated type `Output` (from the trait `std::ops::FnOnce`) must be specified 
--> src/main.rs:3:18 
    | 
3 | struct X(Vec<Box<Boo>>); 
    |     ^^^ missing associated type `Output` value 

有什麼辦法來創建一個特定的FnMut我可以使用 代替FnMut(&[f32]) -> f32的別名?

回答

5

特徵別名目前不是該語言的一部分。但是,這裏有一個accepted RFC。很難預測它的具體實施時間,但接受RFC表示承諾在未來某個時候實施它。

您錯誤的原因是您的Boo特徵是FnMut的子類型,並且任何實現還必須提供所需的關聯類型Output。但是編譯器仍然不知道將提供其實現,所以你需要告訴它的Output類型是什麼:

struct X(Vec<Box<Boo<Output = f32>>>); 

這是有點麻煩,我覺得這是有待改進的領域。直觀上,Output似乎可以從-> f32推斷,但我可能在這裏是錯的。

即使修正了該錯誤,Boo也只是FnMut(&[f32])的子類型,所以您不能僅提供Boo預期的任何關閉。該關閉也必須執行你的特質。你可以做到這一點爲掩蓋實現所有FnMut(&[f32]) -> f32,像這樣:

impl <F> Boo for F where F: FnMut(&[f32]) -> f32 {} 

現在,任何BooFnMut(&[f32]) -> f32(由子類型),以及任何FnMut(&[f32]) -> f32Boo(由毯實現)。

+0

是的,在提出問題之前,我已閱讀了關於此RFC的問題,現在問題是使用當前穩定/ beta編譯器進行的操作。黑客/技巧/ macroses – user1244932

相關問題