"未解决的导入 - 可能是一个缺失的外部"当外部声明存在时

Ben*_*ous 14 rust rust-cargo

我有一个小项目,当它在一个大的.rs文件中时没有问题.我想让它更容易使用,所以我把它分解成模块,现在项目的结构如下:

??? GameState
?   ??? ballstate.rs
?   ??? collidable.rs
?   ??? gamestate.rs
?   ??? mod.rs
?   ??? playerstate.rs
??? lib.rs
??? main.rs
Run Code Online (Sandbox Code Playgroud)

ballstate.rs,我需要使用rand箱子.这是文件的缩写版本:

extern crate rand;

pub struct BallState {
    dir: Point,         
    frame: BoundingBox  
}                     

impl BallState {
    fn update_dir(&mut self) {
        use rand::*;                                                                                                                                                                    
        let mut rng = rand::thread_rng();                                                                      
        self.dir.x = if rng.gen() { Direction::Forwards.as_float() } else { Direction::Backwards.as_float()  };
        self.dir.y = if rng.gen()  { Direction::Forwards.as_float() } else { Direction::Backwards.as_float() };
    }                                                                                                        
}
Run Code Online (Sandbox Code Playgroud)

但是,当我cargo build从顶级目录运行时,我收到以下错误:

GameState/ballstate.rs:42:9:42:13错误:未解决导入rand::*.也许是失踪extern crate rand

当我在main.rs文件中只有extern crate声明时,这很有效.现在有什么变化,它在一个单独的模块中?

DK.*_*DK. 19

引用Rust书Crates and Modules章节:

[...] use声明是绝对路径,从你的箱子根开始.self相反,使该路径相对于层次结构中的当前位置.

编译器是正确的; 没有这样的事情rand,因为你把它放在一个模块中,所以它的正确路径是GameState::ballstate::rand,或者self::rand来自GameState::ballstate模块内部.

您需要移动extern crate rand;到根模块self::randGameState::ballstate模块中使用.