Function declaration order

As mentioned in the book at how-functions-work

Rust doesn’t care where you define your functions, only that they’re defined somewhere.

You can't do that in Python and JavaScript lets you do that and it does something called hoisting.
so, am a little curios, how it works in Rust :thinking: Can someone explain in newbie terms :baby: :wink:

In newbie terms the process of compiling works sort of like this:

  1. Scan all the code making note of all the functions found
  2. Compile the code that may use functions

Nothing is moved like in JS's hoisting, and functions can't be undefined :slight_smile:

3 Likes

When scanning over the source it will determine what functions exist and what types they have before beginning any of the code translation work. If that step passes it will compile a whole crate at once.

You can even see this with the cargo check command, which will verify your code for validity without producing any compiled results (though it will cache the code check results).