我可以在我的 main.rs
中引用 std::f64::NEG_INFINITY
并且没有问题。但是,如果另一个模块引用相同的常量,编译器会报错:Use of undeclared type or module 'std::f64'
。
这是我的main.rs
:
mod bar;
fn main() {
println!("{}", std::f64::NEG_INFINITY);
}
这是我的bar.rs
:
fn foo() {
println!("{}", std::f64::NEG_INFINITY);
}
main.rs
和 bar.rs
在同一个文件夹中。
我做错了什么?
最佳答案
不需要单独的文件;这是一个复制品:
fn main() {}
mod bar {
fn foo() {
println!("{}", std::f64::NEG_INFINITY);
}
}
在你的箱子的根部,std
箱子已经作为 the prelude 的一部分自动导入了。 .从根开始插入路径 std
。
但是,一旦您开始在模块中编写代码,您就不再处于根目录,并且当您尝试使用某个项目时,默认情况下路径是相对的。因此,在 mod bar
内部,路径 std::f64::NEG_INFINITY
将是绝对路径 ::bar::std::f64::NEG_INFINITY
,不存在。
您可以通过两种主要方式解决此问题:
使用
use std;
语句将路径纳入范围。请注意,this 语句默认使用绝对路径,因此 thisstd
是::std
。在每次使用时提供绝对路径:
println!("{}",::std::f64::NEG_INFINITY)
。
关于module - 使用标准库中的模块可以在我的 crate root 中使用,但不能在模块中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40813812/