Sergey Zalizko
Sergey Zalizko

Reputation: 269

Module import fail

I have simple code that imports 2 modules and uses struct from them.
At main.rs I'm using functions from bots/maintrait.rs and gamecore\board.rs They both are imported same way, but func from maintrait.rs cannot be resolved.
Here is structure of my src directory:

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

And code:

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]
        }
    }
...
}

bots\mod.rs

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

bots\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);
          ^~~~~~~~~~~~~

Where I'm wrong? Why 2 same imports works diffirent?

Upvotes: 0

Views: 147

Answers (1)

Shepmaster
Shepmaster

Reputation: 430378

Rust by Example has a good example of how to do something similar.

Here's the appropriate bits of code that need to change:

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();

I'm guessing a bit, but I think the underlying reason is that you haven't really defined a DummyBot::new, but instead have defined a generic Bot::new that DummyBot happens to implement. You have to call the defined method (Bot::new) and provide enough information to disambiguate the call (the type of the let).

Upvotes: 1

Related Questions