The structure of a rust program

Hello world in rust


To start learning a programming language we start by printing hello world message on the screen. Let's do that.

To start :

1 - create a file with extension .rs for example hello.rs and open the file in the code editor

2 - inside file place this code :

fn main(){
    println!("Hello world");
}


3 - To compile and run this command in the folder containing the file :

# to compile replace hello.rs by the name of your file 
rustc hello.rs

# to run
./hello


4 - You will get "hello world" on the screen.


Code explanation


In rust there is 2 types of programs : binary or executable program and library. We will see library later in this course.

1 - Every binary program start it's execution in a special function called main. Here we have :

fn main(){
 
}


fn = keyword to tell the compiler that the following is a function

main = the name of the function, it's a special name.

() = parenthesis is transmit data (called arguments) to this function.

{} = this is function body limits, it's use to hold all code that is part of the function.


2 - instruction

Inside the function body we write statement and expressions that the function will execute. Here we have :

println!("Hello world");

println! = is a macro is rust (we will see them later), here this macro is used to print a message "Hello world" on the the screen.

() = is used to transmit arguments or data to the macro.

"hello world" = is the message to print on the screen.

semi-colon (;) = in rust every statement end with semi-colon, to indicate the end of the statement.