2016-06-09 21 views
0

我可以使用宏而不是特性來構建結構和枚舉。這是一個錯誤還是關於我缺少的特質如何工作?下面是未能建立一個簡單的例子:Do Rust宏在特徵定義內工作嗎?

macro_rules! fun{ 
() => { fn hello(); } 
} 

macro_rules! full_fun{ 
() => { fn hello(){} } 
} 

// Fails with: 
// <anon>:13:8: 13:11 error: expected one of `const`, `extern`, `fn`, `type`, or `unsafe`, found `fun` 
// <anon>:13  fun!(); 
macro_rules! trait_macro{ 
    ($name:ident) => { 
    pub trait $name { 
     fun!(); 
    } 
}; 
} 

macro_rules! struct_macro{ 
    ($name:ident) => { 
    pub struct $name; 

    impl $name { 
     full_fun!(); 
    } 
}; 
} 

// I can add functions to a Impl 
struct_macro!{Monster} 
// But I cannot add functions to a trait 
trait_macro!{Monster} 


fn main() { 

} 
+0

這現在已經實現請參閱[Issue34183](https://github.com/rust-lang/rust/issues/34183) –

回答

0

目前不支持特徵擴展中的宏。相關的AST代碼:

pub enum TraitItemKind { 
    Const(P<Ty>, Option<P<Expr>>), 
    Method(MethodSig, Option<P<Block>>), 
    Type(TyParamBounds, Option<P<Ty>>), 
} 

作爲錯誤消息指出只有constexternfntype,或unsafe預期如在特質下一個標記之一。

1

根據the Rust documentation on macros,宏可以展開爲:

  • 零或多個項目
  • 零或多個方法,
  • 一個表達,
  • 聲明或
  • 模式。

您的full_fun成爲一種方法,但我認爲一個特徵內的聲明不算。 (雖然我還沒有找到確切的參考)。

即使是這樣,它不會幫助:由於宏觀衛生規則,規定不能在其他地方引用,因爲這將有效地是唯一的標識符從任何其他不同的hello - 即你fun!()宏將不應聲明與full_fun!()實施的功能相同。

+0

不要擔心'full_fun!()'它只是在那裏顯示我可以創建函數項並使用它們來填充結構體的impl - 我並沒有試圖實現這個特性。我的'fun!()'宏也擴展爲一個項目。所以應該可以在特質中使用 –