DEV Community

Cover image for Hello World in Rust
Daniel
Daniel

Posted on

1

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.

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️