1

I can reference std::f64::NEG_INFINITY in my main.rs and there is no problem. However, if another module references the same constant, the compiler complains: Use of undeclared type or module 'std::f64'.

Here is my main.rs:

mod bar;

fn main() {
    println!("{}", std::f64::NEG_INFINITY);
}

Here is my bar.rs:

fn foo() {
    println!("{}", std::f64::NEG_INFINITY);
}

main.rs and bar.rs are in the same folder.

What am I doing wrong?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
HiDefender
  • 2,088
  • 2
  • 14
  • 31

1 Answers1

1

No need for separate files; here's a reproduction:

fn main() {}

mod bar {
    fn foo() {
        println!("{}", std::f64::NEG_INFINITY);
    }
}

At the root of your crate, the std crate has been automatically imported as part of the prelude. That inserts the path std starting from the root.

Once you start writing code in a module, however, you are no longer at the root, and when you try to make use of an item, paths are relative by default. Thus, inside of mod bar, the path std::f64::NEG_INFINITY would be the absolute path ::bar::std::f64::NEG_INFINITY, which doesn't exist.

You can solve this in two main ways:

  1. Bring the path into scope by using the use std; statement. Note that this statement uses absolute paths by default, so this std is ::std.

  2. Provide an absolute path at each usage: println!("{}", ::std::f64::NEG_INFINITY).

Community
  • 1
  • 1
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366