2015-10-05 12 views
0

嘗試從模塊中導出宏。宏生成實現模塊中定義的一些特徵的結構。有沒有辦法讓宏手動導入特徵? 如何使用模塊中定義的結構隱式導出宏

// src/lib.rs 
#![crate_name="macro_test"] 
#![crate_type="lib"] 
#![crate_type="rlib"] 

pub trait B<T> where T: Copy { 
    fn new(x: T) -> Self; 
} 

#[macro_export] 
macro_rules! test { 
    ($n:ident) => { 
     struct $n<T> where T: Copy { 
      x: T 
     } 

     impl<T> B<T> for $n<T> where T: Copy { 
      fn new(x: T) -> Self { 
       $n { x: x } 
      } 
     } 
    } 
} 

// tests/test_simple.rs 
#[macro_use] 
extern crate macro_test; 

test!(Test); 

#[test] 
fn test_macro() { 
    let a = Test::<i32>::new(1); 
} 

在這種情況下,我得到一個錯誤:

<macro_test macros>:2:54: 2:61 error: use of undeclared trait name `B` [E0405] 
<macro_test macros>:2 struct $ n <T> where T : Copy { x : T } impl <T> B <T> for $ n <T> 

如果我重寫性狀實現與$crate變量:

impl<T> $crate::B<T> for $n<T> where T: Copy { 

錯誤信息更改爲下一個:

tests\test_simple.rs:8:13: 8:29 error: no associated item named `new` found for type `Test<i32>` in the current scope 
tests\test_simple.rs:8  let a = Test::<i32>::new(1); 
           ^~~~~~~~~~~~~~~~ 
tests\test_simple.rs:8:13: 8:29 help: items from traits can only be used if the trait is in scope; the following trait is implemented but not in scope, perhaps add a `use` for it: 
tests\test_simple.rs:8:13: 8:29 help: candidate #1: use `macro_test::B` 

爲什麼會發生?

回答

2

因爲你不能調用trait方法沒有use性狀。這與宏無關 - 這只是Rust中的一個標準規則。

也許你想讓宏生成一個固有的impl呢?

impl<T> $n<T> where T: Copy { 
    pub fn new(x: T) -> Self { 
     $n { x: x } 
    } 
} 

,而不是你有什麼目前。

+0

不幸的是,在這種情況下。這只是一個綜合的例子,但在工作代碼中是不可能的。好吧,謝謝你的回答,它顯示了我的錯誤。 – Lodin

相關問題