module - 使用标准库中的模块可以在我的 crate root 中使用,但不能在模块中使用

标签 module rust constants

我可以在我的 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.rsbar.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 ,不存在。

您可以通过两种主要方式解决此问题:

  1. 使用 use std; 语句将路径纳入范围。请注意,this 语句默认使用绝对路径,因此 this std::std

  2. 在每次使用时提供绝对路径:println!("{}",::std::f64::NEG_INFINITY)

关于module - 使用标准库中的模块可以在我的 crate root 中使用,但不能在模块中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40813812/

相关文章:

python - python 模块可以有 __repr__ 吗?

performance - Fortran 模块性能

c++ - 传递 const 引用 : performance increase?

c++ - 在 C++ 中引用 const 对象/指针

java - 如何在 Java 代码中使用 Parcelable

types - 在Rust中定义一个异步函数类型

generics - 我如何在 Rust 中编写一个函数来接受其 Item 满足特征的任何迭代器?

rust - 如何在 Rust 中获取当前堆栈帧深度?

c++ - 传递 const &object 与 const object 的区别

compiler-construction - 为什么每次编译 .f 文件后 .mod 文件都不同