Click here to Skip to main content
15,867,488 members
Articles / Programming Languages / Rust
Article

Rust: Your Next Favorite Language - Getting Started Guide (From Zero To Hello World and Beyond)

Rate me:
Please Sign up or sign in to vote.
3.95/5 (12 votes)
26 Apr 2023CPOL6 min read 13.5K   10   2
Get Rust installed, compile and run your first program extremely fast with rustup
All the steps to install Rust and compile your first program. Rust is a great new language to learn and it's a lot of fun to learn in the tradition of K&R C. We'll examine the println!() macro, how to get a file list and how to read from a file.

Why Should You Learn Rust?

There are numerous reasons to learn Rust.

  • It's the easiest compiler / toolchain to install (as we'll see below) which will allow you to build native executables.
Native Exe:

What's a native executable? It's a program that runs directly on the target processor, without any virtual machine or interpreter. This is very cool because if you want to share the executable with someone else running the same OS as you then you can just give them the exe -- no need for them to install massive libraries or interpreters or some runtime (like Java runtime, Python interpreter or .NET CLR)

  • You'll learn programming that is "closer to the metal"

    Similar to what I was saying about the native executable -- your code is compiled to run natively on the processor (there is no runtime environment or interpreter). This means you learn more about the true environment / Operating System that you are running on.

  • Overall Understanding of Programming Will Grow

    You'll learn core concepts of programming. With Rust, you'll learn concepts which are at the "beginning" of programming. Instead of focusing on extremely high-level things like building User Interfaces, you'll learn how computers really work as you learn concepts in Rust.

  • Rust is fun

    Learning to program with Rust is in many ways a simplified programming because you aren't immediately thrown into learning how to create graphical User Interfaces. This removes the burden of being overwhelmed with learning all those extras and makes programming a lot more fun. Learning to program using Rust is similar to how traditional computer programming was learned -- For example, if you've ever read the book, The C Programming Language by Kernighan and Ritchie (K&R C), you'll learn Rust in small code snippets and you'll learn each concept and build on the next. It's a great and fun way to learn to program. But, Rust is a lot more fun to learn than C, because getting everything ready to start writing Rust programs is much easier than getting the C toolchain installed.

Now, let's install Rust.

Install Rust

Windows Install

Install Rustup which will install everything you need and make it easy to update later.

Linux or macOS

Run curl to retrieve rustup:

Rust
$ curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh

Additional Install Help

For more details, check out the official Rust site on installation.

Rust is Installed

If you followed the steps on your system, then Rust is installed.

Now you can open a terminal (aka console) and run the following command:

rustc --version

Here's what I see on my Windows 10 machine:

Image 1

Let's Write Our First Program

  1. Open a console or terminal window (the one you used to run the rustc program will work if you still have it open).
  2. Make a directory to hold your Rust projects. I like a directory under my /home// named dev and then I create a separate folder for each language like: /home/<user>/dev/rust or /home/<user>/dev/c#. Of course, on Windows, that would look like %userprofile%\dev\rust which expands to c:\users\<user>\dev\rust.
  3. Once you create the main rust directory to hold your projects, then go ahead and create a new directory for our first project: On linux $ mkdir ~/dev/rust/hello or on Windows mkdir %userprofile%\dev\rust\hello will create the directory where we want to create our little program.
  4. Now, just change directory into that directory: Linux cd ~/dev/rust/hello or on Windows cd %userprofile%\dev\rust\hello
  5. Create a new Rust source file: On Linux (use the nano text editor), type nano hello.rs or on Windows, use notepad notepad hello.rs
  6. Type in the following program and save it (in nano, you just type Ctrl-X (exit) and then type a 'y' to confirm that you want to save the file).
Rust
fn main() {
   println!("Hello, Rust-world!");
}

Compile the Program

Now for the good part. Just run the rust compiler (rustc)
$ rustc hello.rs It's the same on Windows.

This will compile the program into an executable with the name hello (or hello.exe on Windows).

Run the Program

$ ./hello <ENTER> or on Windows \>hello <ENTER>

You will see the output:

Image 2

You've done it! You've taken your first step to becoming a Rustacean.

But, what have you done?

Program Details: What Have You Done?

main() function

You've created a source file with the main entry point ( a function named main).

Rust Functions

Rust functions have the format:

Rust
fn [name]( [0 or more parameters] )
{
  // function body
}

fn denotes a function in Rust.  If you don't use this keyword, then Rust will not know this is a function.

Rust Requires main() Function

If you rename the function in this small program to something like the main1() and attempt to compile the app again, you will get an error.

Image 3

Rust Has Great Error Information

If you search for that error, you'll find the official web page which gives the following information:

Image 4

Now you know that Rust requires a main() function as an entry point.

That Odd println!() Thing

The only line of code calls println!() to output the text to the standard output.  You probably noticed the exclamation point at the end of the name. That indicates that this is actually a Rust macro being called. This is a helper method which allows you to easily write to standard out.

Rust std (standard) Library

You may have also noticed that we did not have any using or #include statements but we were already able to output to standard out. That's because Rust automatically includes the std library for us. 

Contains All Primitives

std library defines all Rust primitive types which include:

never, array, bool, char, f32, f64, fn, i8, i16, i32, i64, i128, isize, pointer, reference, slice, str, tuple, u8, u16, u32, u64, u128, unit, usize

More about these in a future article.

There are other libraries included for free too.

For example, you can create a Vector of strings and use them quite easily.

Try this code out:

Rust
fn main() {
    println!("Hello, Rust-world!");
    let mut vec = Vec::new();
    vec.push("test 1");
    vec.push("test 2");
    println!("{}",vec[0]);
}

Here, we create a new vector type. 

Mutable Variables Are Not the Default In Rust

However, in order to be able to alter the new variable, we need to use the keyword mut (make variable mutable).

Once we do that, we use the Vector's push method to add two values (two strings).

Finally, we print out the value of the first item in the Vector vec[0] (zero-based indexes) using string interpolation "{}".

What You've Learned

If you've followed along, you've learned:

  1. Various good reasons to learn Rust
  2. How to install rust (using official rustup) which makes it easy to update later (simply type $ rustup upgrade (works on Linux, macOS & Windows)).
  3. That every Rust program needs a main() function.
  4. That functions are defined using the keyword fn.
  5. How to use simply println!() macro and string interpolation.
  6. A basic list of primitive types used in Rust.

To continue down the Rust path, check out the official documentation and follow along.

History

  • 26th April, 2023: First publication

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) RADDev Publishing
United States United States
"Everything should be made as simple as possible, but not simpler."

Comments and Discussions

 
GeneralMy vote of 1 Pin
eran20225-Oct-23 7:43
professionaleran20225-Oct-23 7:43 
GeneralMy vote of 5 Pin
Shao Voon Wong26-Apr-23 15:07
mvaShao Voon Wong26-Apr-23 15:07 
Excellent introduction to Rust!

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.