Great question! Let's break down how Rust handles this situation.
The Code
fn main() { fn_from_std() }
You are asking: How does the Rust compiler know if fn_from_std exists in the standard library or prelude?
1. Name Resolution in Rust
When you write a function call like fn_from_std(), the Rust compiler follows a specific order to resolve what fn_from_std refers to:
-
Local Scope:
It first looks for a function named fn_from_std defined in the current scope (e.g., inside main or at the module level).
-
Imported Items:
Next, it checks for items brought into scope via use statements.
-
Prelude:
If not found, it checks the Rust prelude, which is a set of items automatically imported into every Rust module. The prelude includes common types and traits (like Vec, Option, Result, Clone, etc.), but not arbitrary functions.
-
Standard Library (std):
The compiler does not automatically search the entire standard library for functions. Only items in the prelude or explicitly imported are available.
2. What is in the Prelude?
The prelude contains types and traits, but not free functions. For example, println! is a macro, not a function, and is available because it's part of the prelude.
If you want to use a function from the standard library (that is not in the prelude), you must import it explicitly:
use std::some_module::fn_from_std;
3. What Happens in Your Example?
-
If fn_from_std is not defined in your code and not imported, the compiler will error:
error[E0425]: cannot find function `fn_from_std` in this scope
-
If you want to use a function from the standard library, you must use it.
4. Summary Table
| Location | Automatically available? | How to use? |
|---|
| Local scope | Yes | Just call it |
Imported via use | Yes | use std::foo::bar; |
| Prelude | Yes (types/traits/macros) | Just use it |
| std (not prelude) | No | Must use it |
5. Conclusion
The compiler does NOT search the entire standard library for functions. Only items in the prelude or explicitly imported are available.
So, in your code, unless you define or import fn_from_std, the compiler will not find it.
If you want to see what is in the prelude, check:
https://doc.rust-lang.org/std/prelude/index.html
If you have a specific function in mind, let me know and I can show you how to import it!