DEV Community

Cover image for Hello World in Rust
Daniel
Daniel

Posted on

Hello World in Rust

As a tradition, when learning a new language we write a first program that prints Hello World on the screen so we will do the same.

Create a Project Directory

Create a project directory where you will keep all your work. Open the terminal and write the following commands

$ mkdir ~/rust
$ cd ~/rust
$ mkdir hello_world
$ cd hello_world
Enter fullscreen mode Exit fullscreen mode

Writing and Running a Rust Program

On the current directory create a source file called hello.rs. Now open the file in your code editor and write the code below

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

Save the file and go back to your terminal window and run the file

$ rustc main.rs
$ ./main
Enter fullscreen mode Exit fullscreen mode

The string Hello, world! should print to the terminal. You’ve officially written a Rust program 🎉.

Anatomy of a Rust Program

Let’s review this “Hello, world!” program in detail.

fn main() {

}
Enter fullscreen mode Exit fullscreen mode

This lines define a function called main. The main function is always the first line of code in any executable Rust program.

The body of the main function holds the following code:

println!("Hello, world!");
Enter fullscreen mode Exit fullscreen mode

This line does all the work in this little program: it prints Hello, world! text to the screen.

Top comments (0)