Hello World in Rust

danielmwandiki

Daniel

Posted on July 11, 2024

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.

💖 💪 🙅 🚩
danielmwandiki
Daniel

Posted on July 11, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Data Types
learning Data Types

July 12, 2024

Variables and Mutability
learning Variables and Mutability

July 12, 2024

Getting Started with Rust
learning Getting Started with Rust

July 11, 2024

Hello World in Rust
learning Hello World in Rust

July 11, 2024