“unresolved import — maybe a missing extern” When extern declaration exists

Deadly 提交于 2019-12-03 23:48:57

问题


I have a small project which built with no issues when it was all in one big .rs file. I wanted to make it easier to work with, so I broke it up into modules, and the project is now structured like this:

├── GameState
│   ├── ballstate.rs
│   ├── collidable.rs
│   ├── gamestate.rs
│   ├── mod.rs
│   └── playerstate.rs
├── lib.rs
└── main.rs

In ballstate.rs, I need to use the rand crate. Here's an abbreviated version of the file:

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

However, when I run cargo build from the top level directory, I get the following error:

GameState/ballstate.rs:42:9: 42:13 error: unresolved import rand::*. Maybe a missing extern crate rand?

When I just had the extern crate declaration in my main.rs file, this worked. What's changed now that it's in a separate module?


回答1:


To quote from the Crates and Modules chapter of the Rust book:

[...] use declarations are absolute paths, starting from your crate root. self makes that path relative to your current place in the hierarchy instead.

The compiler is correct; there is no such thing as rand, because you've put it inside a module, so the correct path to it would be GameState::ballstate::rand, or self::rand from within the GameState::ballstate module.

You need to either move extern crate rand; to the root module or use self::rand within the GameState::ballstate module.




回答2:


You need to put the extern crate rand; line in you main.rs and/or lib.rs file. No need to put it in the other files.

Perhaps it is related to this bug.



来源:https://stackoverflow.com/questions/33948293/unresolved-import-maybe-a-missing-extern-when-extern-declaration-exists

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!