Creating your first programs (rustc)

Ok so from here on out we assume that Rust is properly installed and Visual Studio Code is properly configured.

We'll start by writing our first program and compiling it using the Rust compiler, called rustc.

Hello World

On your Desktop, create a folder and let's call it data-with-rust. Start Visual Studio Code and open that folder (File > Open Folder...) by selecting it in the popup.

In Visual Studio Code, create a new file and let's call it helloworld.rs (rust-analyzer might complain here but let's ignore it for now).

Save the following in the helloworld.rs file:

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

Now go to Terminal > New Terminal in Visual Studio code and run the following:

# first this
rustc helloworld.rs

# and then this
./helloworld

The result should look like this:

Running hello world

Notice the cool output in the terminal! Your first Rust program just joyfully welcomed the world, completely unaware of what's ahead.

What just happened?

You just wrote, manually compiled and ran your first Rust program, congratulations! πŸŽ‰

What this means is that you used the Rust compiler, to instruct your computer to create a file called helloworld (without the .rs at the end) that you can run on your machine. We "ran" this file by writing ./helloworld in the terminal. This file is commonly called a binary or executable, it's executable machine code.

In 2023 lingo, we kinda created an app because (without going too much into details yet) here's the thing: You can now copy the helloworld file on a USB stick and run it on another computer of the same type (Mac/Unix/Windows), it will work without the need of having Rust installed on the target machine.

Isn't that neat? Trying to do something in Python is a bit complicated and might frustrate you a bit. I know because I've been there.

##Β Let's make it a bit more interesting

Replace the code in the helloworld.rs file with the following:

use std::io;

fn main() {
    println!("What is your name?");

    let mut name = String::new();

    io::stdin().read_line(&mut name)
        .expect("Failed to read input.");

    println!("Hello, {}! Welcome to the world of Rust!", name.trim());
}

Now in the same terminal, run and respond to the question:

rustc helloworld.rs

./helloworld
# What is your name?

If everything went properly, the terminal should greet you now with your own name. Again, this executable is portable and will work on all the systems of the same type as the machine it was compiled on.

Running hello world next

What have we learned?

We can now write, manually compile and also run our own Rust programs. Isn't that super neat?

Here's a fun fact, the Rust compiler that you used to create the Rust executable, is itself primarily written in Rust!

Next, we'll see how we can enhance our developer workflow without having to manually compile our Rust programs from scratch, like we just did.