“未解决的导入——可能是缺少 extern";当外部声明存在时 [英] "unresolved import -- maybe a missing extern" When extern declaration exists
问题描述
我有一个小项目,它在一个大的 .rs 文件中构建时没有问题.我想让它更容易使用,所以我把它分解成模块,现在项目的结构是这样的:
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
在ballstate.rs
中,我需要使用rand
板条箱.这是该文件的缩写版本:
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() };
}
}
但是,当我从顶级目录运行 cargo build
时,出现以下错误:
However, when I run cargo build
from the top level directory, I get the following error:
GameState/ballstate.rs:42:9: 42:13 错误:未解析的导入 rand::*
.也许缺少 extern crate rand
?
GameState/ballstate.rs:42:9: 42:13 error: unresolved import
rand::*
. Maybe a missingextern crate rand
?
当我的 main.rs 文件中有 extern crate 声明时,这有效.现在它在一个单独的模块中有什么变化?
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?
推荐答案
[...] use
声明是绝对路径,从你的 crate 根开始.self
使该路径相对于您在层次结构中的当前位置.
[...]
use
declarations are absolute paths, starting from your crate root.self
makes that path relative to your current place in the hierarchy instead.
编译器正确;没有rand
这样的东西,因为你已经把它放在一个模块中,所以它的正确路径应该是GameState::ballstate::rand
,或者<GameState::ballstate
模块中的 code>self::rand.
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.
您需要将extern crate rand;
移动到根模块或在GameState中使用
模块.self::rand
::ballstate
You need to either move extern crate rand;
to the root module or use self::rand
within the GameState::ballstate
module.
这篇关于“未解决的导入——可能是缺少 extern";当外部声明存在时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!