2014-12-13 120 views
0

我有簡單的代碼,導入2個模塊並使用它們的結構。
main.rs我使用的是從機器人/ maintrait.rsgamecore \ board.rs他們都是進口的方式一樣,但FUNC從maintrait.rs功能不能得到解決。
這裏是我的src目錄的結構:模塊導入失敗

. 
├── bots 
│   ├── maintrait.rs 
│   └── mod.rs 
├── gamecore 
│   ├── board.rs 
│   └── mod.rs 
└── main.rs 

和代碼:

main.rs

use gamecore::{GameBoard,State}; 
use bots::{Bot,DummyBot}; 

mod bots; 
mod gamecore; 

fn main() { 
    let board = GameBoard::new(); 
    let bot = DummyBot::new(State::O); 
    board.make_turn(State::X, (0, 0)); 
    board.make_turn(State::O, bot.get_move(&board)); 
} 

gamecore \ mod.rs

pub use self::board::{GameBoard,State}; 
mod board; 

gamecore \ board.rs

pub struct GameBoard { 
    field: [[State, ..3], ..3] 
} 

impl GameBoard { 
    pub fn new() -> GameBoard { 
     GameBoard { 
      field: [[State::Empty, ..3], ..3] 
     } 
    } 
... 
} 

機器人\ mod.rs

pub use self::maintrait::{Bot,DummyBot}; 
mod maintrait; 

機器人\ maintrait.rs

use gamecore::{GameBoard,State}; 
use std::rand; 

pub trait Bot { 
    fn new<'a>() -> Box<Bot + 'a>; 
    fn get_move(&mut self, board: &GameBoard) -> (uint, uint); 
} 

pub struct DummyBot { 
    side: State 
} 

impl Bot for DummyBot { 
    fn new<'a>(side: State) -> Box<Bot + 'a> { 
     box DummyBot{ 
      side: side 
     } 
    } 

    fn get_move(&mut self, board: &GameBoard) -> (uint, uint) { 
     let turn = rand::random::<uint>() % 9; 
     (turn/3, turn % 3) 
    } 
} 

ERROR MESSAGE

10:28 error: failed to resolve. Use of undeclared module `DummyBot` 
let bot = DummyBot::new(State::O); 
      ^~~~~~~~~~~~~ 
10:28 error: unresolved name `DummyBot::new` 
let bot = DummyBot::new(State::O); 
      ^~~~~~~~~~~~~ 

我在哪裏錯了?爲什麼2個相同的進口工作不同?

+0

我猜想從子模塊中的'DummyBot'實現trait的問題,但我不知道如何解決這個問題,而不破壞代碼結構。 – 2014-12-13 15:47:01

回答

1

Rust by Example有一個很好的例子,說明如何做類似的事情。

下面是需要改變的代碼的相應位:

pub trait Bot { 
    // Your trait and implementation signatures differ, so I picked this one 
    fn new() -> Self; 
} 

impl Bot for DummyBot { 
    fn new() -> DummyBot { 
     DummyBot{ 
      side: State::Empty 
     } 
    } 
} 

let bot: DummyBot = Bot::new(); 

我猜了一點,但我認爲,根本原因是,你還沒有真正定義一個DummyBot::new,而是定義DummyBot碰巧實現的通用Bot::new。您必須調用定義的方法(Bot::new提供足夠的信息以消除呼叫(let的類型)。