RUST: Begin the Journey with CODE

Hope so you have already gone through the first blog RUST: Quick Start & Exploring Cargo” and ready to workout with your fingers and keys.

You might be thinking about the basic programming concepts of RUST as a language. With the help of an example, I will try to cover the following points (practically):

  • mutable, immutable variables
  • Standard input/output (console)
  • Functions
  • Data type and conversion
  • Loops: while, loop, for, continue, break
  • Pattern matching
  • Exception Handling
  • Collections: Vector, HashMap, Iterator

Let’s solve a problem of aggregation, adding the values for the same category. I will try to demonstrate this with a practical example of stock and total stock holding.

Starting with the standard/console input-output and a dedicated function that returns the value as a tuple to print on console. Copy paste the below code in a new file main.rs and execute as you learned in the previous blog :

This code snippet will take the input of the stock name and its value from console and give the same as output to verify the working. So let’s, now understand the code one by one.

Note: Rust follows snake_case instead of camelCase, rustc (Rust compiler) will give warning in case of camelCase convention. 

let (name, value) = read_io();
println!(“Stock name: {}, value: {}”, name, value);

In the above line (main function), First, we are calling a function read_io() which will return us a tuple of string (stock name) and i32 number (stock value) as an immutable variable (by default all variable are immutable in Rust). We will talk in detail about the data type and immutability in the coming blog related to them. In the next line, we are calling println! macro function to print the variables on the console.

use std::io;

Rust includes few types into the scope of every program by default, but for the other not in the scope, we need to bring it into the scope explicitly with a use statement. Using the above statement brings a library into the scope which provides us with useful features, to accept user input from the console.

Hope you are clear with the main() function code. Let’s start with the read_io() function:

fn read_io() -> (String, i32)

-> (String, i32) defines that the function read_io() will return a tuple of 2 variables,  first one will be of String data type and another one is i32 i.e. signed 32 bits numeric value to use unsigned we can use u32 instead of i32 for more detail we will discuss this in data type blog.

Here, we have used mut before name to declare it as a mutable variable, String::new() call new method of String library. (:: operator is used to accessing the library functions, by default String is in the scope of every program).

Next line, stdin() function of I/O library is called to read the user input from the console, read_line() need a mutable String variable to write the line input the variable that’s the reason to create the name as mutable (& indicates the reference of the variable). expect() function is used to handle the failure case if any happens in reading the line and print the message written in it as a parameter (Failed to read name) to the console.

In the next part, we have used a loop to read the value (i32) as the input from the console is always a String, so to ensure about the numeric we need to explicitly parse it and check the value to be numeric before going further.

Here, parse() function is used to convert String to i32, this function can create a panic situation (exception) if the value is not a number. In Rust, this is dealt with a match and a block which has ok(num) and Err(_) function to handle the situations (exception) accordingly. Now, we will continue to execute the loop code until we get a numeric value.

Note: String value read contain ‘\n’, we need to trim it and parse with to_string() before returning it, as it is a reference instead of a string value.

Let’s move to the actual code (download code file from git) and discuss how to store the inputs using collections (HashMap and Vector) and calculate the total valuation for each stock.

let mut stock_sum_map: HashMap<String, Vec> = HashMap::new();

Here, we are creating a mutable HashMap of String key (stock name) and value Vec for the list of values of each stock(key).

I am skipping the check_io_flag() functionality for you to understand it, as it much similar to read_io().

stock_sum_map.entry(name).or_insert(Vec::new()).push(value);

In the above code, we are using entry(_) method which returns an enum called Entry that represents a value that might or might not exist. Next, we have called or_insert(_) method on the Entry which will return a mutable reference to the value for the key if that key exists, and if not, inserts the parameter (Vec::new()) as the new value for the key and returns a mutable reference to the new value.

push(value) is a method of Vector library which will add the value into the vector reference (mutable) returned by the previous method (or_insert).

for (name, vector) in stock_sum_map {

In the above code snippet, after reading values from the console input and storing it in the map, we are using for each loop over the map to fetch each (key, value) pair from the reference.

let total_value: i32 = vector.iter().sum();
println!(“Stock name: {}, total Value: {}”, name, total_value);

Now, with the reference of the Vector containing values of the stock (key), we can directly aggregate it in RUST using the sum() method over the iterator (.iter().sum()).

In the last line, we have printed the total value of each stock with stock to the console.

You can download the code from the git link, and execute the code as already explained in the first blog.

Reference: The Rust Programming LanguageKnoldus-Scala-Spark-Services

Written by 

Sourabh Verma is a Software Consultant with experience of more than 2 years. He has a deep understanding of Java and familiar with Spring Framework, JPA, Hibernate, JavaScript, Spark, Scala, AngularJS, Angular 4. He is an amazing team player with self-learning skills and a self-motivated professional. He loves to play with Real-time problems, Big data, Cloud computing, Agile Methodology and Open Source Technology. He is eager to learn new technologies and loves to write blogs and explore nature.

Leave a Reply

%d bloggers like this: