Making a "Hello World" program in Rust
The journey to learning any programming language starts with a simple “Hello World” program. To create a “Hello World” program in Rust, follow these steps:
- Create a source file and name it
main.rs– rust files always end with the.rsextension. - Open the
main.rsfile and write the following code in it:
fn main() {
println!("Hello world!");
}
- Save the file and open a terminal window in the directory you are working in.
- If you are using Linux or MacOS, enter the following commands to execute the program:
$ rustc main.rs
$ ./main
- If you are using Windows, then the commands to compile and execute the program are:
> rustc main.rs
> .\main.exe
The following is an executable “Hello World” program in Rust:
fn main() {println!("Hello World!");}
Explanation
-
The code
fn main() {}defines a function namedmain. Themainfunction is special because it is always the first code that runs in a Rust executable program. Any arguments will go inside the parenthesis()and the code will go inside the curly brackets{}. -
The code
println!("Hello, world!");simply prints the string inside the parenthesis onto the screen. Note thatprintln!has an exclamation mark at the end of it – this means that it is a macro and not a function. While functions generate a function call, macros are expanded into a source code that is compiled with the rest of the program.
Free Resources