Get Started with Rust: Installation and Your First CLI Tool – A Beginner’s Guide
Rust has become a popular programming language in recent years as it combines security and high performance and can be used in many applications.It combines the positive characteristics of C and C++ with the modern syntax and simplicity of other programming languages such as Python.
In this article, we will take a step-by-step look at the installation of Rust on various operating systems and set up a simple command line interface to understand Rust’s structure and functionality.
Installing Rust — step by step
Regardless of the operating system, it is quite easy to install Rust thanks to the official installer rustup, which is available for free on the Rust website.
This means that the installation only takes a few steps and only differs slightly for the various operating systems.
Installing Rust under Windows
In Windows, the installer completely controls the installation, and you can follow the steps below:
Go to the “Install” subsection on the official Rust website (https://www.rust-lang.org/tools/install)" style="color: #0066cc;">https://www.rust-lang.org/tools/install) and download the rustup-init.exe file there.
The website recognizes the underlying operating system so that the appropriate suggestions for the system used are made directly.
As soon as the download is complete, the rustup-init.exe file can be executed.
A command line with various installation instructions then opens.
Press the Enter key to run the standard installation to install Rust.
This also includes the following tools:
rustc is the compiler, which compiles the code and checks for errors before execution.
cargo is Rust’s build and package management tool.
rustup is the version manager.
After successful installation, Rust should automatically be available in your PATH.
This can be easily checked in PowerShell or CMD using the following commands:
rustc --version cargo --version
If “rustc” and “cargo” are then displayed in the output with the respective version numbers, then the installation was successful.
However, if the command is not found, it may be due to the environment variables.
To check these, you can follow the path “This PC –> Properties –> Advanced system settings –> Environment variables”.
Once there, you should make sure that the path to Rust, for example “C:\Users\UserName\.cargo\bin”, is present in the PATH variable.
Installing Rust under Ubuntu/Linux
In Linux, Rust can be installed completely via the terminal without having to download anything from the Rust website.
To install Rust, the following steps must be carried out:
Open the terminal, for example, with the key combination Ctrl + Alt + T.
To install Rust, the following command is executed:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs" style="color: #0066cc;">https://sh.rustup.rs | sh
3.
You will then be asked whether the installation should be started.
This can be confirmed by entering “1” (default), for example.
All required packages are then downloaded, and the environment is set up.4.
You may have to set the path manually.
In this case, you can use this command, for example:
source $HOME/.cargo/env
After the installation has been completed, you can check whether everything has worked properly.
To do this, you can explicitly display the versions of rustc and cargo:
rustc --version cargo --version
Installing Rust under macOS
There are several ways to install Rust on macOS.
If you have installed Homebrew, you can simply use this to install Rust by executing the following command:
brew install rustup rustup-init
Alternatively, you can also install Rust directly using this script:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs" style="color: #0066cc;">https://sh.rustup.rs | sh
During the installation, you will be asked whether you want to run the standard installation.
You can simply confirm this by pressing the Enter key.
Regardless of the variant selected, you can then check the installation by displaying the version of Rust to ensure that everything has worked:
rustc --version
cargo --version
Creating a Rust project with cargo
During the installation of Rust, you have probably already come across the cargo program.
This is the official package manager and build system of Rust and is comparable to pip in Python. cargo performs the following tasks, among others:
Initialization of a project
Management of dependencies
Compiling the code
Execution of tests
Optimization of builds
This allows you to manage complete projects in Rust without having to deal with complicated build scripts.
It also helps you to set up new projects quickly and easily, which can then be filled with life.
For our example, we will create a new project.
To do this, we go to the terminal and navigate to a folder in which we want to save it.
We then execute the following command to create a new Rust project:
cargo new json_viewer --bin
We call this project json_viewer because we are building a CLI tool that can be used to open and process JSON files.
The --bin option indicates that we want to create an executable program and not a library.
You should now be able to see the following folder structure in your directory after executing the command:
json_viewer/
├── Cargo.toml # Project configuration
└── src
└── main.rs # File for Rust Code
Every new project has this structure. Cargo.toml contains all the dependencies and metadata of your project, such as the name, the libraries used, or the version.
The src/main.rs, on the other hand, later contains the actual Rust code, which then defines the steps that are executed when the program is started.
First, we can define a simple function here that generates an output in the terminal:
fn main() {
println!("Hello, Rust CLI-Tool!");
}
The program can be easily called up from the terminal using cargo:
cargo run
For this call to work, it must be ensured that you are in the main directory of the project, i.e.
where the Cargo.toml file is stored.
If everything has been set up and executed correctly, you will receive this output:
Hello, Rust CLI-Tool!
With these few steps, you have just created your first successful Rust project, which we can build on in the next section.
Building a CLI tool: Simple JSON parser
Now we start to fill the project with life and create a program that can read JSON files and output their content in the terminal in a structured way.
The first step is to define the dependencies, i.e., the libraries that we will use in the course of the project.
These are stored in the Cargo.toml file.
In Rust, the so-called crates are comparable to libraries or modules that offer certain predefined functionalities.
For example, they can consist of reusable code written by other developers.
We need the following crates for our project:
serde enables the serialization and deserialization of data formats such as JSON or YAML.
serde_json, on the other hand, is an extension that was developed specifically for working with JSON files.
For your project to access these crates, they must be stored in the Cargo.toml file.
This looks like this immediately after creating the project:
[package]
name = "json_viewer"
version = "0.1.0"
edition = "2021"
[dependencies]
We can now add the required crates in the [dependencies] section.
Here we also define the version to be used:
[dependencies]
serde = "1.0"
serde_json = "1.0"
To ensure that the added dependencies are available in the project, they must first be downloaded and built.
To do this, the following terminal command can be executed in the main directory:
cargo build
During execution, cargo searches the central Rust repository crates.io for the dependencies and the specified versions to download them.
These crates are then compiled together with the code and cached so that they do not have to be downloaded again for the next build.
If these steps have worked, we are now ready to write the actual Rust code that opens and processes the JSON file.
To do this, you can open the src/main.rs file and replace the existing content with this code:
use std::fs;
use serde_json::Value;
use std::env;
fn main() {
// Check arguments
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
println!(“Please specify the path to your file.”);
return;
}
// Read in File
let file_path = &args[1];
let file_content = fs::read_to_string(file_path)
.expect(“File could not be read.”);
// Parse JSON
let json_data: Value = serde_json::from_str(&file_content)
.expect(“Invalid JSON format.”);
// Print JSON
println!(" JSON-content:\n{}”, json_data);
}
The code follows these steps:
Check arguments:
We read the arguments from the command line via env::args().
The user must specify the path to the JSON file at startup.
Read the file:
With the help of fs::read_to_string(), the content of the file is read into a string.
Parse JSON:
The crate serde_json converts the string into a Rust object with the type Value.
Format output:
The content is output legibly in the console.
To test the tool, you can, for example, create a test file in the project directory under the name examples.json:
{
"name": "Alice",
"age": 30,
"skills": ["Rust", "Python", "Machine Learning"]
}
The program is then executed using cargo run and the path to the JSON file is also defined:
cargo run ./example.json
This brings us to the end of our first project in Rust and we have successfully built a simple CLI tool that can read JSON files and output them to the command line.
This is what you should take with you
Installing Rust is quick and easy in many operating systems.
The other components that are required are already installed.
With the help of cargo, an empty project can be created directly, which contains the necessary files and in which you can start writing Rust code
Before you start Programming, you should enter the dependencies and download them using the build command.
Now that everything is set up, you can start with the actual programming.
The post Get Started with Rust: Installation and Your First CLI Tool – A Beginner’s Guide appeared first on Towards Data Science.
Source: https://towardsdatascience.com/get-started-with-rust-installation-your-first-cli-tool-a-beginners-guide/" style="color: #0066cc;">https://towardsdatascience.com/get-started-with-rust-installation-your-first-cli-tool-a-beginners-guide/
#get #started #with #rust #installation #and #your #first #cli #tool #beginners #guide
Get Started with Rust: Installation and Your First CLI Tool – A Beginner’s Guide
Rust has become a popular programming language in recent years as it combines security and high performance and can be used in many applications.
It combines the positive characteristics of C and C++ with the modern syntax and simplicity of other programming languages such as Python.
In this article, we will take a step-by-step look at the installation of Rust on various operating systems and set up a simple command line interface to understand Rust’s structure and functionality.
Installing Rust — step by step
Regardless of the operating system, it is quite easy to install Rust thanks to the official installer rustup, which is available for free on the Rust website.
This means that the installation only takes a few steps and only differs slightly for the various operating systems.
Installing Rust under Windows
In Windows, the installer completely controls the installation, and you can follow the steps below:
Go to the “Install” subsection on the official Rust website (https://www.rust-lang.org/tools/install) and download the rustup-init.exe file there.
The website recognizes the underlying operating system so that the appropriate suggestions for the system used are made directly.
As soon as the download is complete, the rustup-init.exe file can be executed.
A command line with various installation instructions then opens.
Press the Enter key to run the standard installation to install Rust.
This also includes the following tools:
rustc is the compiler, which compiles the code and checks for errors before execution.
cargo is Rust’s build and package management tool.
rustup is the version manager.
After successful installation, Rust should automatically be available in your PATH.
This can be easily checked in PowerShell or CMD using the following commands:
rustc --version cargo --version
If “rustc” and “cargo” are then displayed in the output with the respective version numbers, then the installation was successful.
However, if the command is not found, it may be due to the environment variables.
To check these, you can follow the path “This PC –> Properties –> Advanced system settings –> Environment variables”.
Once there, you should make sure that the path to Rust, for example “C:\Users\UserName\.cargo\bin”, is present in the PATH variable.
Installing Rust under Ubuntu/Linux
In Linux, Rust can be installed completely via the terminal without having to download anything from the Rust website.
To install Rust, the following steps must be carried out:
Open the terminal, for example, with the key combination Ctrl + Alt + T.
To install Rust, the following command is executed:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
3.
You will then be asked whether the installation should be started.
This can be confirmed by entering “1” (default), for example.
All required packages are then downloaded, and the environment is set up.4.
You may have to set the path manually.
In this case, you can use this command, for example:
source $HOME/.cargo/env
After the installation has been completed, you can check whether everything has worked properly.
To do this, you can explicitly display the versions of rustc and cargo:
rustc --version cargo --version
Installing Rust under macOS
There are several ways to install Rust on macOS.
If you have installed Homebrew, you can simply use this to install Rust by executing the following command:
brew install rustup rustup-init
Alternatively, you can also install Rust directly using this script:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
During the installation, you will be asked whether you want to run the standard installation.
You can simply confirm this by pressing the Enter key.
Regardless of the variant selected, you can then check the installation by displaying the version of Rust to ensure that everything has worked:
rustc --version
cargo --version
Creating a Rust project with cargo
During the installation of Rust, you have probably already come across the cargo program.
This is the official package manager and build system of Rust and is comparable to pip in Python. cargo performs the following tasks, among others:
Initialization of a project
Management of dependencies
Compiling the code
Execution of tests
Optimization of builds
This allows you to manage complete projects in Rust without having to deal with complicated build scripts.
It also helps you to set up new projects quickly and easily, which can then be filled with life.
For our example, we will create a new project.
To do this, we go to the terminal and navigate to a folder in which we want to save it.
We then execute the following command to create a new Rust project:
cargo new json_viewer --bin
We call this project json_viewer because we are building a CLI tool that can be used to open and process JSON files.
The --bin option indicates that we want to create an executable program and not a library.
You should now be able to see the following folder structure in your directory after executing the command:
json_viewer/
├── Cargo.toml # Project configuration
└── src
└── main.rs # File for Rust Code
Every new project has this structure. Cargo.toml contains all the dependencies and metadata of your project, such as the name, the libraries used, or the version.
The src/main.rs, on the other hand, later contains the actual Rust code, which then defines the steps that are executed when the program is started.
First, we can define a simple function here that generates an output in the terminal:
fn main() {
println!("Hello, Rust CLI-Tool!");
}
The program can be easily called up from the terminal using cargo:
cargo run
For this call to work, it must be ensured that you are in the main directory of the project, i.e.
where the Cargo.toml file is stored.
If everything has been set up and executed correctly, you will receive this output:
Hello, Rust CLI-Tool!
With these few steps, you have just created your first successful Rust project, which we can build on in the next section.
Building a CLI tool: Simple JSON parser
Now we start to fill the project with life and create a program that can read JSON files and output their content in the terminal in a structured way.
The first step is to define the dependencies, i.e., the libraries that we will use in the course of the project.
These are stored in the Cargo.toml file.
In Rust, the so-called crates are comparable to libraries or modules that offer certain predefined functionalities.
For example, they can consist of reusable code written by other developers.
We need the following crates for our project:
serde enables the serialization and deserialization of data formats such as JSON or YAML.
serde_json, on the other hand, is an extension that was developed specifically for working with JSON files.
For your project to access these crates, they must be stored in the Cargo.toml file.
This looks like this immediately after creating the project:
[package]
name = "json_viewer"
version = "0.1.0"
edition = "2021"
[dependencies]
We can now add the required crates in the [dependencies] section.
Here we also define the version to be used:
[dependencies]
serde = "1.0"
serde_json = "1.0"
To ensure that the added dependencies are available in the project, they must first be downloaded and built.
To do this, the following terminal command can be executed in the main directory:
cargo build
During execution, cargo searches the central Rust repository crates.io for the dependencies and the specified versions to download them.
These crates are then compiled together with the code and cached so that they do not have to be downloaded again for the next build.
If these steps have worked, we are now ready to write the actual Rust code that opens and processes the JSON file.
To do this, you can open the src/main.rs file and replace the existing content with this code:
use std::fs;
use serde_json::Value;
use std::env;
fn main() {
// Check arguments
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
println!(“Please specify the path to your file.”);
return;
}
// Read in File
let file_path = &args[1];
let file_content = fs::read_to_string(file_path)
.expect(“File could not be read.”);
// Parse JSON
let json_data: Value = serde_json::from_str(&file_content)
.expect(“Invalid JSON format.”);
// Print JSON
println!(" JSON-content:\n{}”, json_data);
}
The code follows these steps:
Check arguments:
We read the arguments from the command line via env::args().
The user must specify the path to the JSON file at startup.
Read the file:
With the help of fs::read_to_string(), the content of the file is read into a string.
Parse JSON:
The crate serde_json converts the string into a Rust object with the type Value.
Format output:
The content is output legibly in the console.
To test the tool, you can, for example, create a test file in the project directory under the name examples.json:
{
"name": "Alice",
"age": 30,
"skills": ["Rust", "Python", "Machine Learning"]
}
The program is then executed using cargo run and the path to the JSON file is also defined:
cargo run ./example.json
This brings us to the end of our first project in Rust and we have successfully built a simple CLI tool that can read JSON files and output them to the command line.
This is what you should take with you
Installing Rust is quick and easy in many operating systems.
The other components that are required are already installed.
With the help of cargo, an empty project can be created directly, which contains the necessary files and in which you can start writing Rust code
Before you start Programming, you should enter the dependencies and download them using the build command.
Now that everything is set up, you can start with the actual programming.
The post Get Started with Rust: Installation and Your First CLI Tool – A Beginner’s Guide appeared first on Towards Data Science.
Source: https://towardsdatascience.com/get-started-with-rust-installation-your-first-cli-tool-a-beginners-guide/
#get #started #with #rust #installation #and #your #first #cli #tool #beginners #guide
·68 Views