Rust is a relatively new but popular programming language with a syntax similar to C++.  The concepts informing its design are high performance and safety (particularly safety in concurrent operations and memory).  The language has received support from Google on the Android project, and Microsoft has also been increasingly adopting it.  As a result, learning Rust is a solid investment for any programmer or computer science student with an eye on industry trends.

Introductory Programming

Let’s start by taking a look at the traditional “Hello World!” program written in Rust:

// This is the main function

fn main() {

    // Statements here are executed when the compiled binary is called

    // Print text to the console

    println!("Hello World!");


Much like in other C family languages, such as C++, comments in Rust are denoted by “//” or alternatively by a pair of “/*” and “*/” symbols to open and close block comments respectively.  If you’re unfamiliar, comments are non-executable descriptive text that can be used to document your code and will not affect the final compiled program. 

The fn keyword denotes the introduction and definition of a function, which in this case is the main() function that forms the entry point for compiled code when it is executed.  Using the same syntax as C/C++, the function definition is enclosed in a pair of braces to define its start and end, and manage the scope of the code within.

println! is a macro (the exclamation mark being what denotes it as a macro, rather than a function) which can be used to write text to the console (i.e. io::stdout).  The println! macro can be supplied with arguments by using braces (“{}”) or with numbers in braces to use positional arguments, for example:

    println!("Hello {}!”, “Alice”);

    println!("{0}, this is {1}. {1}, this is {0}.", "Alice", "Bob");

This second example would print out “Alice, this is Bob.  Bob, this is Alice.”  Using numbered parameters and positional arguments in this way allows you to reuse them in a single string without specifying them multiple times.

Primitive Types

Rust provides a wide range of primitive types that can be used to represent numbers, characters, text, logical states, and sets.  The language also allows developers to define custom types via structures or enumerations.

Variables can be declared either explicitly or their type can be derived from context.  For example:

    let bool_example: bool = true;

    let float_example: f64 = 1.5;

    let integer_example = 5i32;

This last example is known as suffix notation as the type (a 32-bit integer) is specified as a suffix to the value allocation.  Nonetheless these are all examples of explicit type declaration.  To leave the type to be inferred, we can use the mut keyword to signify that the variable is mutable:

    let mut inferred_var = 12;

    inferred_var = 4294967296i64;

As you can see, although the variable is initially declared as an integer (which would default to a 32-bit integer in this case, as the value is small enough to fit in 32 bits), the second use of the inferred variable sets it to a 64 bit integer.  This does not, however, mean that you could change to another type altogether – the following is not valid:

    let mut inferred_var = 12;

    inferred_var = true;

To do this, we would need to use a feature called shadowing, by reusing the let keyword:

    let mut inferred_var = 12;

    let inferred_var = true;

Remember, use of the mut keyword alone is not sufficient to be able to overwrite the type of a variable.  An alternative way to achieve a similar effect is to make use of variable scope, which would allow you to redeclare a variable using let alone as long as it’s in a local scope (i.e. enclosed in braces) with a technique called shadowing:

let my_var = 1;


    println!("Value before being shadowed: {}", my_var);


    let my_var = "abc";

    println!("Value while shadowing: {}", my_var);


println!("Outside of local scope: {}", my_var);

The output of this sample would first be as follows:

Value before being shadowed: 1

Value while shadowing: abc

Outside of local scope: 1

This is because the shadowed variable only exists for as long as the local scope in which it was defined.

Arrays are another important use of primitives, and follow a familiar syntax.  Take the following example, which creates a single dimension array of 5 integers comprising of the numbers 1 through 5:

let array_example: [i32; 5] = [1, 2, 3, 4, 5];

It’s also possible to define an array and initialise it entirely with the same value by separating the value and number of instances of that value with a semicolon, as follows:

let array_example: [i32; 50] = [0; 50];

Arrays are zero-indexed and accessible through familiar square-bracket notation (e.g. array_example[0]), and sections of them can be borrowed as slices using the following notation, allowing them to be manipulated on their own and passed to functions:

&array_example[1 .. 3]


Flow Control

Rust utilises the standard flow control mechanics you’d expect from a C-family language, including if/else, while- and for- loops, as well as a few others. 

if/else constructions are slightly different to other languages in syntax.  Firstly, the condition statement doesn’t require brackets around it, and the if block itself is an expression where each branch can return a value (albeit of the same type).  For example, consider first this basic if/else statement in terms of basic syntax:

let n = 2;

if n < 5 {

    print!(“n is less than 5”);

} else if n >= 5 {

    print!(“n is 5 or more”);


This is relatively unremarkable, but becomes more interesting when we make use of assigning an output from the different branches of the block:

let n = 10;

let result =

    if n < 5 {

        “less than 5.”

    } else {

        “5 or more.”


print!(“{} is {}”, n, result);

Note in particular the lack of semicolons on the last statement of each branch of the if statement, and the addition of a semicolon to the closing brace which completes the let result = block.  This is because all let statements must terminate with a semicolon.

while statements follow the syntactical style of an if block by omitting the traditional brackets around the loop condition, and behave as one might expect from a C-family loop.  Consider this example of a FizzBuzz implementation provided by the official Rust language ‘learn Rust by example’ documentation:

fn main() {

    // A counter variable

    let mut n = 1;


    // Loop while `n` is less than 101

    while n < 101 {

        if n % 15 == 0 {


        } else if n % 3 == 0 {


        } else if n % 5 == 0 {


        } else {

            println!("{}", n);



        // Increment counter

        n += 1;



An implementation of the above in a for loop is similarly achieved, but instead of

    let mut n = 1;

    while n < 101 {

we can simply declare the opening and closing values in a for statement like so:

    for n in 1..101 {

This means you don’t have to manually increment n at the end of the loop either, and thus can omit the last statement:

    n += 1;

Other flow of control topics include iterators, used with for loops to create a foreach style iteration, the match keyword which allows switch style statements from C, and if let and while let statements to make match more usable in various circumstances.

Code Structure

In Rust, code is written in functions which can be organised into modules.  Modules allow programs to be split over multiple files and divided across different namespaces.  This is an advancement over what can be achieved in C, which does not provide namespace functionality, and analogous to similar functionality in C++ and C#.  The mod keyword allows a programmer to define a block into a module with a certain name, for example:

// In the file

mod my_module {

    fn Hello () {

        println!(“Hello World!”);



A consumer can then make use of the module by including the mod keyword in another file and then invoking the function:

// In a separate file

mod my_module;

fn main() {



However, if you run this example you will see it does not work and you receive an error stating that the method is private.  This is because rust defaults all members of a module to private, and we must instead manually declare which aspects of it are to be public, forming its interface.  These are familiar object-oriented programming concepts that give us the capability of encapsulation, and enable us to hide code implementation from a consumer.  In order to declare a module’s item as being public, it must be prefaced by the keyword pub, such as in the following example:

mod my_module {

    pub fn Hello () { … }


Taking this concept a little further introduces us to the concept of crates.  Crates are compilation units within Rust; whenever a .rs Rust file is compiled (using rustc), the input file is treated as a crate file.  In practical terms, this means that when the input file contains mod declarations, the contents of the relevant module file is inserted in place of those mod declarations before the compiler is run.  This means that modules themselves do not get individually compiled; only crates do.  Crates can be either binary files or a library, defaulting to a binary.  You can override the behaviour of the compiler for a crate using the –crate-type flag and setting its value to lib when you call rustc.

Sitting over the top of modules and crates, Rust has its own package manager called Cargo, which contains a publicly available repository of crates.  This enables developers to publish and reuse common functionality across different projects and organisations, rather than being forced to reimplement a concept every time it is required.

The Rust Programming Environment and Tools

Now that we’ve looked at some of the elementary concepts around programming in Rust, the best next-step would be to get involved and start writing code to build up your knowledge.  A wide range of IDEs support rust, including VS Code, Eclipse and Atom.  When combined with the Rust Language Server you’ll have access to rich features such as code formatting and autocompletion to support you as you learn.  A particularly useful tool for beginners is Rust Clippy which analyses your code to catch common mistakes and increase your familiarity with idiomatic Rust-native code.

Why students should use our service

As you spend more time developing your skills across various programming languages, no matter what object you’re trying to meet, we have tutors available to help with any problems you might encounter. Our expert tutors can help with any aspect of Rust programming, other languages, or general programming concepts such as OOP or multithreading.  We can offer live tutors or provide writeup deliverables, where a tutor can deliver you clearly written, production quality code with accompanying detailed descriptions and documentation.  More advanced students facing larger challenges will also find no shortage of help from our experts, who can help guide the design and development of your programs, or simply provide advice and feedback to help you make code changes and revisions should you get stuck.  Regardless of the complexity of your requirements, our seasoned veteran computer scientists are ready to help.

24HourAnswers has been helping students as an US-based online tutoring business since 2005, and our tutors have worked tirelessly to provide students with the best support possible. We are proud to be A+ rated by the Better Business Bureau (BBB), a testament to the quality support delivered by our tutors every day. We have the highest quality experts, with tutors from academia and esteemed institutions such as the Massachusetts Institute of Technology (MIT).

Should you be interested in pursuing a career in this exciting field, remember that our homework help centre is standing by 24/7 to help assist you in all aspects of computer science.

Alexander Sofras is a solution architect with over 20 years of programming experience and 12 years in industry.  He currently works in finance and specializes in the Azure cloud platform.

Some suggested further reading:
Get College Homework Help.

Are you sure you don't want to upload any files?

Fast tutor response requires as much info as possible.

Upload a file
Continue without uploading

We couldn't find that subject.
Please select the best match from the list below.
For faster response, you may skip assigning directly to a tutor to receive the first tutor available.
That tutor may not be available for several hours. Please try another tutor if you're in a hurry.

We'll send you an email right away. If it's not in your inbox, check your spam folder.

  • 1
  • 2
  • 3
Get help from a qualified tutor

Latest News

Read All News
April 20, 2021

New subject available! Quantitative Methods

Hey students! is proud to annouce that we've added another topic to our Business subject area. You can now receive online tutoring for Quantitative Methods. You can learn more about Quantitative Methods at   -24HourAnswers team
April 12, 2021

$500 College Scholarship Deadline

Just a reminder to our students and website visitors that the deadline for the Spring semester scholarship is May 1st. To learn more about applying, please visit our blog.  
Live Chats