"unresolved import -- maybe a missing extern" 当外部声明存在时
"unresolved import -- maybe a missing extern" When extern declaration exists
我有一个小项目,当它全部在一个大的 .rs 文件中时,构建没有任何问题。我想让它更容易使用,所以我把它分解成模块,现在项目的结构是这样的:
├── GameState
│ ├── ballstate.rs
│ ├── collidable.rs
│ ├── gamestate.rs
│ ├── mod.rs
│ └── playerstate.rs
├── lib.rs
└── main.rs
在 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() };
}
}
但是,当我从顶级目录 运行 cargo build
时,出现以下错误:
GameState/ballstate.rs:42:9: 42:13 error: unresolved import rand::*
. Maybe a missing extern crate rand
?
当我的 main.rs 文件中有 extern crate 声明时,它起作用了。现在它在一个单独的模块中有什么变化?
您需要将 extern crate rand;
行放入 main.rs
and/or lib.rs
文件中。不需要放在其他文件中。
可能与this bug有关。
引用自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.
编译器正确;没有 rand
这样的东西,因为您已将它放在模块中,所以它的正确路径是 GameState::ballstate::rand
,或者 GameState::ballstate
中的 self::rand
模块。
您需要将 extern crate rand;
移动到根模块 或 在 GameState::ballstate
模块中使用 self::rand
。
我有一个小项目,当它全部在一个大的 .rs 文件中时,构建没有任何问题。我想让它更容易使用,所以我把它分解成模块,现在项目的结构是这样的:
├── GameState
│ ├── ballstate.rs
│ ├── collidable.rs
│ ├── gamestate.rs
│ ├── mod.rs
│ └── playerstate.rs
├── lib.rs
└── main.rs
在 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() };
}
}
但是,当我从顶级目录 运行 cargo build
时,出现以下错误:
GameState/ballstate.rs:42:9: 42:13 error: unresolved import
rand::*
. Maybe a missingextern crate rand
?
当我的 main.rs 文件中有 extern crate 声明时,它起作用了。现在它在一个单独的模块中有什么变化?
您需要将 extern crate rand;
行放入 main.rs
and/or lib.rs
文件中。不需要放在其他文件中。
可能与this bug有关。
引用自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.
编译器正确;没有 rand
这样的东西,因为您已将它放在模块中,所以它的正确路径是 GameState::ballstate::rand
,或者 GameState::ballstate
中的 self::rand
模块。
您需要将 extern crate rand;
移动到根模块 或 在 GameState::ballstate
模块中使用 self::rand
。