【问题标题】:Module import fail模块导入失败
【发布时间】:2014-12-13 15:27:58
【问题描述】:

我有导入 2 个模块并从中使用结构的简单代码。
main.rs 我正在使用来自 bots/maintrait.rsgamecore\board.rs 的函数它们都以相同的方式导入,但是maintrait.rs 中的 func 无法解析。
这是我的 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]
        }
    }
...
}

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)
    }   
}

错误信息

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 个相同的导入工作不同?

【问题讨论】:

  • 我猜想子模块的DummyBot 的实现特征有问题,但我不知道如何在不破坏代码结构的情况下解决这个问题。

标签: module rust


【解决方案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 的类型)。

【讨论】:

    猜你喜欢
    • 2019-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-03
    • 2020-03-30
    • 2019-03-30
    • 2021-09-24
    相关资源
    最近更新 更多