sciencenotes.medium.com 5 min read Original Source

Rust Programing For Beginners in 6 Mins!

Once, my colleague asked: “Have you ever heard about Rust programming? It is a new programming language, not object-oriented and much faster than C++”. Well, I had not heard and used it by then. However, the question inspired me enough to learn how to program with Rust. Afterward, I enrolled in a Udemy course: Rust Programming For Beginners, and started immediately to learn it. In this article, I would like to share what I learned, which covers almost half of the course.

The superiority of Rust over lots of programming languages, including C++, is the system of ownership that manages memory automatically. In Rust, the owner of the memory is the variable, and the memory cannot have more than one owner at a time. To access the value stored in memory, we can borrow them. Otherwise, ownership is moved to the new variable. If it seems to be complicated, don’t worry! Just keep this in mind. I will explain this more in the following sections.

Basics

  • Data types

In Rust, Data types are Boolean (true, false), Integer (i32, i64), Float or Double (f32, f64), Character (char), and String (str).

The String data type is a bit more complicated than the others to work with. I will explain it later more in the next section.

  • Comments

Same as C++, you can create comment by double slash //.

  • variables

We can assign Data to a variable by keyword let:

[Embedded content: 5dccec487f27faa4ed5226ccc1c3a43f]

By default, variables are immutable. For creating a mutable variable, we must to explicitly declare it by let mut:

[Embedded content: d3aecc3a167e4942fbc2db6c8ddb9629]

. Mathematic operations

Mathematic operations are Plus +, minus -, multiply *, divide /, and quotient %.

Data handling in Rust

  • Enum

Enum is short for enumeration, and it is a type for creating items or variants. The enum’s name and variants must be Capital case. For example, to create an enum for different colors:

Enum is a type to represent one item at a time and each item is called variant. Learn more about enums in 3 Fundamentals of Enums in Rust.

[Embedded content: d4ea8f9018ae13879979da468b13e7b9]

  • Struct

Struct is short for structure, and it creates a structured object with multiple properties or data. For example, to create a “User” object with properties including name, nationality, height, weight, and eye color:

[Embedded content: d1ed9e25e67c700f1a09bda798ae6e43]

As you can see, properties in the structure could be of different types. But it is necessary to specify the type of each property in the structure. In this example, the user’s name is String type while the eye color is Eyecolor enum we created above. In the next section, you will see that we can do more with structures.

  • Tuples

A tuple is a collection of data, objects, or variables with the same or different types. A tuple is created by (), and it is handy to store a collection of data with different types in order. For example:

[Embedded content: 1b116a7b1877f93a53dca959a297192c]

The indices start with zero, so with numbers.0 we can access the first element of numbers.

  • Vectors

A vector is a collection of data, objects or variables only with the same types. We can create vectors by vec macro or by Vec structure. For example, to create a vector of usernames:

[Embedded content: e96270080e8791dfcaf9ee43ff648adc]

To access the element of a vector [] is used. For example the third username is usernames[2].

  • Strings

Strings data type is more complicated than integers or floats. As you can see, the name of the user in the User struct is String type. However, to create an instance of the user, we cannot write name: "Sara". If we do so:

[Embedded content: ffece30fb04efa4a04ac2680b9d254d6]

we face the expected struct String, found &str“ error. It means that a text like "Sara" is not an owned String, but it is an borrowed String (&str). We can create an owned string by name: "Sara".to_owned() or name: "Sara".to_String(). Therefore, to create a vector of Users:

[Embedded content: da2af9d2259e5f45721d515e0ecc4b9e]

Functions in Rust

The keyword for creating a function in Rust is fn. We have to specify the parameters types if we pass any to a a function. In a function signature, we specify the type of each parameter by :. If the type is not simple data types such as integer, floats or Booleans, we must borrow it using an ampersand &. Otherwise, the memory is moved to the function and the ownership of the variable will be dropped. For example, to write a function for printing usernames:

[Embedded content: 9f28893d5e0ef664fdacdc640fce70be]

In this example, we can used a borrowed string type to print a text: print("Sara").

As another example, to write a function for calculating user’s BMI based on weight and height:

[Embedded content: 09795576994723e3b5701a1540ce5dad]

In this example, the function borrows an instance of the User struct, take the weight and height of the user to compute BMI and returns a float.

Conditional expressions

  • if else

If-else is the most common type of conditional expressions; if some condition holds, do something. For example, if BMI of a user is less than 25 he/she is normal, if is is between 25 and 29 he/she is overweight, and more than 29 is obese. To program this we say:

[Embedded content: bb994503a445ee0ed0c1d1c400d9a302]

In the first line, we create a variable named sara_bmi and using bmi function and users vector we created earlier we compute Sara’s BMI.

  • Match

Well, Match is a condition that considers all the cases. It is similar to switch in C++, but it is not equivalent. However, it can handle more data type. I believe it makes program smarter, so that we don’t miss any case by mistake. For example:

[Embedded content: c651cd62acd1390be4be6fc80540325f]

In this example, I created a variable named user_eyecolor and for each case I want to make a guess. If user’s eye color is blue, I guess he/she is from Germany, if it is green, from Russia, otherwiese (_), I have not guess.

Loops in Rust

  • For

For iterating over all elements of a data collection, such as vectors, we use for loops. For example, to compute the BMI of all the users and print out the name and BMI per user:

[Embedded content: 184d671423f3e87117645ca330d534bb]

As another example, to compute the mean of users BMI

[Embedded content: 48fdea105433973e5c85319bad8b7d5a]

In this example, I created a mutable variable named bmi_sum, to sum user’s BMI in a for loop, and an immutable num_users which is the length of users vector in the above examples. Then, divided BMI sum by the number of users. Note that we have to declare that num_users should be taken as a float. Otherwise, we will get a compiler error as a float-integer division is not possible in Rust.

  • While

Repeating a command while some condition is true is done by a while loop. For example, to create a vector of the user’s BMI:

[Embedded content: 6aa28bf02048dff5e73cdce6707afff7]

In this example, I created a mutable-iterative variable, i, and an empty vector for the user’s BMI. This should also be mutable because it is empty, and we want to fill it in each iteration. As I mentioned, using the Vec struct, we can create a vector, and new() is a function of the Vec structure that creates an empty vector. Using the push() function, we can add a member to the vector.

  • Loop

Same as match, loop is a new feature in Rust. It is very similar to the while loop, and the idea is the same; do something until break. To do the previous example with loop loop!

[Embedded content: 84d0136508dcb632ea0ccb1d74a182d4]

As you can see, I put a condition for break in the loop. Otherwise if we get index out of bounds error!

Functions under the structures in Rust

The last two examples might seem more complicated because I didn’t talk about functions under the structure so far. In the last two examples, new and push are two functions under the Vec structure.

In Rust, we can write functions for a specific structure using imlp. To me, it is similar to the methods for the class in object-oriented programming languages. To call such functions, :: is used, and to apply a structure function to the structure itself, . is used.

For example, to add a function new() for creating a new instance of the User:

[Embedded content: ea067ce0cf800b0238b4eac96959d142]

In this example, new() returns an instance of User struct. See the summary for the usage and complete examples!

Summary

To recap, write a program to create a collection of users and compute mean of users BMI:

[Embedded content: 39272fe33a55133df0c3c247384cd40f]

In this example, I brought all the previous examples in one. Go line by line to review all you learned in this tutorial 😊.

Conclusion

In this article, you learn basic programming with Rust. If you have not programmed before, it might not be enough for you. But, if you have, I believe it is handy to get started. Besides, Rust has provided comprehensive tutorials here if you want to dig into more. To continue learning Rust, check out Rust programing for beginners [part 2] and [part 3].😊.

**Join Medium to read great tutorials and stroies! **

  • I write Machine Learning, Deep Learning and Data Science tutorials. Upgrade to read more.*