DEV Community

Cover image for RUST 101 πŸ¦€ (Ep 01)
Kenechukwu Marvellous
Kenechukwu Marvellous

Posted on

RUST 101 πŸ¦€ (Ep 01)

Anatomy of a Rust program

So, let's say you want to write a Rust program that prints

( Hello, World! )
Enter fullscreen mode Exit fullscreen mode

when you run it.

This is an example of what that code would look like:

fn main() {
println!("Hello, world!");
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Rust is a compiled and strongly typed systems language, and it needs a clearly defined starting point and structure.

Without

fn main( )
Enter fullscreen mode Exit fullscreen mode

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)