Hello Rust for First Timers

ยท

8 min read

Featured on Hashnode

For the past 5 years in a row, Rust has topped the Most Loved Programming (MLP) Languages according to StackOverflow Survey. This category of languages is usually robust, intentional, and simple. They give developers who use them some superpowers that are difficult to find in other Languages.

Research has shown that Newbies and Junior devs are not very concerned with MLP languages. They - MLPs - are more harnessed by the seniors. While Newbies are known to favor Python and Javascript, they miss the sugar and goodness of the MLP languages usually with a wrong assumption that they are more difficult. My intuition tells me this could be faulted by the lack of many newbie-targeted materials. I hope this article fills the gap.

In this Hello Rust article, you will see for yourself how super simple and robust Rust is. I briefly discussed the problems I've seen Rust solve. After which you will build a simple calculator project with the language. Trust me the process will be slow, smooth and enjoyable.

๐Ÿ’€

This writing is targeted at audiences who are:

  • newbies to programming, and

  • first-time Rust enthusiasts.

I'll be assuming you do simple commands on the CLI, and you have hands-on experience coding with something as rudimental as HTML and CSS.

It is nice to know that this article intentionally skips a lot of concepts. If you are looking for a more detailed introduction, this is not the article.

Set up your environment ๐Ÿ”ง๐Ÿ› โš™

๐Ÿ’€

You should skip this section on the following conditions that

  • you've already set up a Rust environment

  • you would be using Rust Playground

The creator of Eslint, Nicholas C. Zakas, wrote an excellent post on setting up a Rust development environment with Visual Studio Code. Whether or not you use Visual Studio Code, you will find it useful to set up. Kindly read the blog as a guide to set yourself up. I'll wait.

Get Started

Now that you are all set up, do the following:

  1. Create a folder. This folder is intended to be where our code resides. In our case, I'll name mine Rust.

  2. Create an hello.rs file inside the newly created Rust folder. `hello.rs` is a rust file, and rust files end with a `.rs` extension.

  3. Compile the file by running rustc hello.rs in a terminal. Henceforth, when I mention compile I mean calling the rustc hello.rs command.

  4. You should see an error with error[E0601]: 'main' function not found in crate 'hello...'

OMG ๐Ÿ˜ฒ you just compiled and made a bold attempt to master Rust. Isn't that wonderful ๐Ÿคฉ?


Let's make the error in 4 above disappear. Before we do that, let me tell you something โš .

Entry Point

Rust enforces only one entry point to your code (there is another way but that's beyond our scope now). Presuming you are coming from a free-for-all language like JavaScript, this might be strange. But with this little strictness comes one of the reasons Rust is easy to read.

The entry point is the main function ๐ŸŽ‡. Rust will read your program only from this function. This may sound confusing hence let's get down to some code already.

Your First Rust Code

Inside your hello.rs file, copy and paste the code below.

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

After successfully writing or pasting the code, follow these instructions:

  1. Compile the code: rustc hello.rs. This will create a hello.exe file in the same folder.

  2. Run the exe file: If you use Linux or WSL enter ./hello in the terminal and click enter, and for windows users use .\hello.exe.

You should see a shiny "Hello World" Program ๐ŸŽ‰๐Ÿ™Œ.

Try to break the code to see if rust will compile outside a main function. Rename the main function to mainr. Then compile the code. You should see an error warning: function mainr is never used.

You could have used another name aside mainr. But be rest assured if a main function does not exist, Rust isn't going to be happy.

Function in Rust

A function encapsulates blocks of code for reuse.

In best practices, a function is meant to return a value. There are two ways to return a value in Rust:

  • without a return keyword. In this case, the line must not end with a semi-colon ;.

  • with a return keyword. You are at liberty to add a semi-color or not.

Choosing the type to use on a codebase depends on a lot of factors.

For example, on a personal project, those with a JavaScript background will prefer to use the return keyword. This is because in JavaScript the return keyword is used to return a value in a function.

Unlike someone who is from a Python background, they may prefer to use the type without the keyword.

On a team codebase, a consensus has to be reached on what way to ensure uniformity.

See the two ways to return a value in Rust.


// TYPE 1
fn foo (){
  4
}

// TYPE 2
fn foo2 (){
  return 4;
}

You should then use this custom function inside the body of your main function. Compile and run the code.

fn foo () {
  4
}

fn main (){
  println!("{}", foo());
}

You will see an error try adding a return type: '-> i32' ๐Ÿ˜ . Well I am sorry but in Rust, custom functions must have a return type and a parameter type.

fn foo ()->i32 {
  4
}

fn foo2 ()-> i32{
  return 4;
}

You can compare the example in this section with the first one. Tell me the changes you saw. Exactly, a return type -> i32. This leads us to the next to talk about.

๐ŸŽ‰ you got yourself a working code at last.

Strongly Typed

Rust is a strictly typed language. The intention is to make our code easier to read and faster to know the intentions of our variables, functions etc.

If you decide to stop reading this chapter out of fear of types, I can assure you it is only a misconception. Types are so so simple. They are extra notes used to restrict our values.

I really won't want to bore you with the nitty-gritty of types in this article. Henceforth I will refer to all number types as i32 - signed integer of base 32. I will also limit this article to using numbers.

fn foo ()->i32 {
  4
}

fn main (){
  println!("{}", foo());
}

Compile your code and it works.

Our calculator

Our calculator is meant to do only addition and subtraction. Hopefully, I've made you realize how simple Rust can be. You can move on to add division, multiplication etc after this article. With no further ado, let's dive in.

We will start out by writing an add function

fn add (a: i32, b: i32)-> i32{
  return a + b;
}

And then substract

fn subtract (a: i32, b: i32)->i32 {
  return a - b;
}

In our main function, we have a little calculator ๐ŸŽ‰.

...
fn main () {
  println!("{}", add(23, 45));
  println!("{}", subtract(23, 45))
}

The limitation with our calculator.

When you try to run a decimal with our function, it won't work ๐Ÿ˜ข. I am sorry it is time to bore you with some popular number types and their meaning.

// floating/decimal number won't work
fn main () {
  println!("{}", add(23.4, 45));
  println!("{}", subtract(23, 45.3))
}

i32 represents a signed integer of 32 bits. 32 bits are calculated as (2^n-1) - 1 where n = 32. interpreted as ((2 raise to power 32 - 1) - 1). This type enforces that our numbers fall between the negative and positive values of the mathematical result of 32 bits. But the number must not be a decimal. Only integers.

f32 is the type used to represent a decimal that falls within the same range as i32.

To make our calculator work for decimals replace i32 with f32.

fn add (a: f32, b: f32)-> f32{
  return a + b;
}

fn subtract (a: f32, b: f32)-> f32{
  return a - b;
}

When you compile this code, you will get an error expected 'f32', found integer help: use a float literal: '23.0'. Well, it is complaining that it expects one of our parameters to be a floating number but found an integer.

This can be frustrating. But we have a way out, TypeCasting. It is best to cast an integer into a floating number instead of otherwise.

fn add (a: f32, b: f32)-> f32{
    return a + b;
  }

  fn subtract (a: f32, b: f32)-> f32{
    return a - b;
  }

  fn main () {
    println!("{}", add(23.4, 45 as f32));
    println!("{}", subtract(23 as f32, 45.3))
  }

And yes, you have yourself a calculator as promised. I can't wait to see what you will do next. I hope this article gave you the perfect push to learn rust even as a beginner. You can see it isn't as difficult as it seems. You too can boast of using the MLP languages now ๐Ÿ˜….

If this sparked your interest, you should consider reading the Rust Book or perhaps subscribe to my articles. My next article will be on a proper introduction to Rust. A build on this Hello Rust article.

Talk to me on Twitter at kelvinsekx. Bye.

ย