Anatomy of a Rust program
So, let's say you want to write a Rust program that prints
( Hello, World! )
when you run it.
This is an example of what that code would look like:
fn main() {
println!("Hello, world!");
}
Running this code βπΌ will produce the desired output. But why didn't we just write
Hey,
Display (hello, world)
on my screen and it works? Why do we have to follow the format shown above?
I'll explain the code above bit by bit, detailing what each element means and does.
Let's dive in.
fn
β’ fn is short for function.
β’ A function is a block of code that performs an action.
β’ Not all code is a function.
β’ However, the starting point of a program must be a function, and that function is called "main
."
β’It's the entry point. The beginning. The commander-in-chief.
β’If you remove main()
, Rust wonβt know where to start and will throw an error:
error: cannot find function `main` in this crate
Rust is a compiled and strongly typed systems language, and it needs a clearly defined starting point and structure.
Without
fn main( )
the compiler wouldnβt know:
β’ Where to begin execution
β’ How to manage scope, stack, variables, lifetimes, etc.
Rust is optimized for performance, safety, and control, so structure matters a lot.
We'll talk about main in the next episode. Stay rusty ππ¦
Top comments (0)