Rust programing for beginners [part three]
The third part of tutorials for Rust programming for beginners includes input/output, external crate, read and write JSON files, and building executables in Rust.
Welcome to another tutorial in Rust programming for beginners series. This tutorial covers mainly interacting with users by reading and writing inputs and answers the following questions:
- How to read user inputs in Rust?
- What is a crate in Rust?
- How to use an external crate in Rust?
- How to read and write JSON files in Rust?
- How to create an executable in rust?
1. Input / Output
The standard Input/Output (io for short) library in Rust is std::io. It contains functionality for interactive programming, reading the user inputs, and writing the outputs.
Some of the important module of std::io are:
io::Resultis a type defined bystd::io. It is a Resultenumthat returns the type or error.io::stdin()is the standard input.io::stdin().readline()is the standard input function. It takes a mutable string and appends it to the string inserted by the user. It returns theio::Resultif the result isOK()the size of the inserted string, else an error.
Example: Let’s write a program that takes the user’s weight and height and gets the user’s BMI.
Here, I have created a get_input() function, which takes a message to request the user what should be inserted. Then, in the main() function, the name, weight, and height are asked. Since the weight and height are not String, we must parse them to floats.
[Embedded content: c6deccd39c24a90103745eab587e6cc1]
We can save the user input into a variable in two different ways. get_input() returns io::Result, therefore, we should match over io::Result or unwrap() it. In this example, I tried both; for name and weight, I directly unwrap() the result, while for the height, I match over Ok() and Err(). The advantage of the second method is to catch the error and print it.
2. External crate
In Rust programming language, the compilation unit is called crate. A crate is usually one or more .rs files.
The internal crate is a .rs file in the project. For example, if the project has file_1.rs and file_2.rs, use crate::file_1 to call file_1.rs into file_2.rs:
use crate::file_1;
use crate::file_1;
External crates are Rust libraries or packages. Find the list of available libraries for Rust at https://crates.io/.
2.1. Use external crate
After creating a new project (see here to learn how to create a new project), the cargo.toml file is created that configures the project at the top. By default, [dependencies] section is empty:
To use an external crate, we should include the library name and version in this section. For example, to use to use serde and serde-json for reading and writing JSON files:
Then, it will be possible to use functionally provided by the library in Rust files. Let’s try doing so by the following example!
2.2. Example: Read and write json files in Rust
To keep it simple, assume we have a simple structure for the user:
[Embedded content: f3f57b622fbaf70141f9d563330d08f0]
and the users are stored in a JSON file:
The goal is to ask the user’s name, weight, and height and add the new user to the JSON file. We fulfill the goal in the following steps:
- read the JSON file and deserialize it to a vector of
Users; implemented inread_users(). - ask user to enter name, weight, and height; same as section 1.
- add new user to the vector; line 55.
- serialize the vector to string; line 57.
- write the new user to the JSON file; implemented in
write_users().
[Embedded content: 413742b5373a5215b9ac1aa2610a3b20]
The result will be as following:
Note: I avoid long explanation for the functions in the example. I find it very boring to explain a lot about few lines of codes. I would be happy if you could share what you think about tutorials. By the way, I would be I am not sure it’s the best way. If someone knows a better, I would be appreciative to learn.
3. Cargo Command!
Cargo commands are handy to manage Rust projects. This section is a short summary of Hello, Cargo!
cargo new: creates a new project. See more in part 2.cargo check: checks if the code get compiles or not.cargo run: compiles and runs the resulting output.cargo build: creates an executable in Rust. After running this command, anexefile is created for eachrsfile in the project folder/target/debug. Note that the executable close immediately if there is no interaction with the user.cargo build --release: does the same thing but in/target/debug.
Summary
In this tutorial, I share my experience in creating a simple user interactive project in Rust. I believe this tutorial is very useful because, After learning how to use external crate in Rust, the journey in Rust programming starts. From now on, we can create more interesting project and learn faster.
I collect all the examples in the series in a this git repository. For the next tutorial, I plan to talk about expressions, implementations and testing in Rust. So, stay tuned😊.
Join Medium to read great tutorials and stories!
I write Machine Learning, Deep Learning and Programming tutorials. Upgrade to read more.
