Rust programing for beginners [part two]
In Rust Programming For Beginners [part 1], I introduced basic concepts in Rust programming. In this tutorial, I introduced some more advanced concepts including,
- Closures
- Iterators
- Traits
- Modules
If you’ve just started learning Rust, I highly recommend reading Rust Programming For Beginners [part 1]. If you are here to learn about the concepts mentioned above, check out the examples in Rust Programming For Beginners [part 1] because we aim to continue working on them in this tutorial.
1. Enums
In Rust Programming For Beginners [part 1], I introduced Enums in Rust. Read 3 Fundamentals of Enums in Rust for some advanced notes about Enums. Here, we expand the example of the first part. Assume we have a structure called User:
[Embedded content: f82e8a2d76cfd1b7e803801db84d7cd3]
where EyeColor is an enum for different eye colors, and Gym is an enum for gyms with membership IDs.
2. Closures
Closures are unnamed functions that capture the environment inside pipes ||. Inside pipes, we can write our parameters.
Closures are different from function in:
- For functions, we use parenthesis, (), but for closures, we use pipes, ||.
- Functions must have names, but it is not required for closures.
- Type annotation is inferred for closures but is mandatory for function.
- Closures cannot be defined separately. But we create them inside the functions.
[Embedded content: cca066abcbec0d4fed8a1d9e5edbd107]
In this example, bmi is a closure to compute BMI given weight and height. Call this by let my_bmi = bmi(57., 1.60);. However, closures are not meant to be used separately instead of functions. But, they are used mainly inside other functions. For example, as an argument for map() or filter() combinators. You will see more about this later on in this tutorial.
3. Iterators
Iterators are a simple way to do a for loop over the collection of Data. iter() creates an iterator that goes through the specified data collections, for example, a vector. To manipulate elements, we chain iter() with a map() or other combinators.
Below, I created a vector of user struct, using the new() function for the User (explained in part 1).
[Embedded content: 13cfbb96a4b7d25fe2ea3cb5763cfb72]
We plan to compute the BMI of the users and store them in another vector. We did the same thing with basic concepts in part 1. Here we use iter() chained with map().
3.1. map combinator
One of the common use of closures is with map combinator. map() takes a function (closure) as an argument to transform one member. In other words, map() is a shorter way of writing a function and applying it to the data.
In part 1, we created bmi() function to compute users’ BMI based on their weights and height. Using map(), we can do the same thing as follows:
[Embedded content: 37a980448131c48b09a1203b4367f30b]
Here, we iterate over users vector and compute BMI for each element. Then, To get output from the iterator and save the output in user_bmi vector, we collect() the result.
This way, we can write shorter, easy to read, and cleaner code. We can also call map multiple times, or chain other combinators or functionality.
In a similar way, we can compute the average BMI:
[Embedded content: cfabbeaba2c1ec9cdb799918af4eeec7]
average_bmi() takes a vector of Users, computes BMI for each User, sums up the results, and divides it by the length of the vector.
3.2. Frequently used functions on iterators
filter(closure)filters out items by some conditions. The condition is a closure with a single argument that returns a boolean.find(closure)is similar tofilter(). It filters out items by some condition but returns only the first item that satisfies the condition. Another difference is that the output offind()is an option. If it finds an item, it returnsSome(data type). Otherwise, it returnsNone.count()returns the number of items within the iterator.min()returns the minimum element of the data structure. It returns an option type;Nonewhen the iterator is empty.max()is similar tomin()but for maximum.last()returns an option type which is the last item of the iterator;Nonewhen the iterator is empty.take(index)takes one item from the iterator by the given index.next()returns the next item as an option type. When it reaches out to the last item, it returnsNone.
To play around with some of them, consider the following example.
[Embedded content: afec3ac7d4828598388e7851a70f77df]
We compute BMI and filter out the obes users. We are interested in min and max.
[Embedded content: 646067757046560d05fb6791266e9029]
In the above example, the chained functions execute in order. Meaning that, first, BMIs are computed. Next, the obes users are filtered. Then the number of obes users is counted.
3.3. Range
Similar to Python, the range creates a sequence of values automatically. To summarize, look at the following table.
The range becomes handy when we need a list of consecutive values or to get a range of items in a data structure. For example, below, we print out the BMI of the first two obes users.
[Embedded content: 01003456fa8653cf89265464247f21a0]
4. Traits
Traits are a way to define a shared functionality for several types. Normally, we need to define methods for each type. However, traits enable us to group “shared behavior”.
For example, the length of a Vector is the number of items, while the length of a String is the number of characters. In this simple example, the functionality is unique; length. But, the way to compute the length is different for vector type or string type.
In our project, we’d like to group users and gyms. User and Gym are structs; users by BMI and gyms by area or size. We aim at calling the group like this: user.whatgroup() or gym.whatgroup().
[Embedded content: f38965d00f725d0013be5ce23a68de89]
To do so, we create a trait called Group. Then, we implement the trait for each type, User and Gym. For each, we compute a measurement. Then based on that, we decide about the group.
5. Modules
Modules are similar to a class in C++. Modules enable us to organize the code and different functionality. They might contain Enums, structs, or functions.
For example, let for the vector of Users, we need different utility functions such as average user weights, height, or BMI. Therefore we create a module called utils that contains such functionality.
The keyword to create a module is mod. Below, I’ve written three methods (functions) for the module named utils. In Rust, members or methods of a module are private by default. So, we cannot use them outside of the module. To make them available outside the module, we have to use keyword pub before the function definition.
Note: use crate::*; in the first line, gives utils access to all structures, enums, functions, etc. For example, utils need to have access to the User defined earlier.
[Embedded content: 69082848ad6344e76d26d061d278a7c6]
To call the functions outside of the modules, for instance average_bmi(), we say utils::average_bmi(&users).
5.1. Modules as a Separate files
It’s time to create our first Rust project. But, how to create a new rust project? Simplly:
- Open command prompt.
- cd to the desired path for your first project
- write
cargo new [project_name] --bin
Your new project consists of a Cargo.toml and a main.rs inside the src folder. To run hello world, write cargo run main in your terminal.
Let’s create two modules called user.rs and utils.rs; user.rs contains all of the structures, enums, and traits we’ve created so far, and utils.rs contains the above utility function. Remember! to access the members of modules, we have to make them public using keyword pub.
Then:
- Create a folder in
src, and call it something, for example,modules. - Inside module create a
mod.rsfile. - In mod.rs import user.rs and utils.rs by
pub mod user;
pub mod utils;
pub mod user;
pub mod utils;
-
Create
lib.rsin the same level with src. -
In lib.rs import modules by
pub mod modules; -
In
Cargo.tomlcreate a key called[lib], and specify the name and path oflib.rs
[lib]
name = "lib"
path = "src/lib.rs"
[lib]
name = "lib"
path = "src/lib.rs"
Now, we are able to use user and utils as separate modules by:
use lib::modules::user;
use lib::modules::utils;
use lib::modules::user;
use lib::modules::utils;
Note: In order to use traits inside modules, we need to import them separately. For example, if we insert trait Group defined above in user.rs, we should import it separately:
use lib::modules::user::Group;
use lib::modules::user::Group;
If it looks complicated, take a look at this git repository.
Summary
In this tutorial, we took one more step toward learning the Rust programming language. I’ve tried my best to explain the concepts as clear as possible in a short way. Besides, I collect all the examples in the series in a small git repository. Anyhow, if you have any questions, please ask in the comments. Moreover, I would be happy about any suggestions and comments for making the stories better.
Check out the next tutorial, Rust programing for beginners [part 3] to learn more 😊.
**Join Medium to read great tutorials and stroies! **
- I write Machine Learning, Deep Learning and Data Science tutorials. Upgrade to read more.*


![Rust programing for beginners [part three]](https://freedium-mirror.cfd/img/medium/4000/1*rbAHb6wM55zrH5vskkLvkg.jpeg)