保留正文与补采附件。源页面当前未重新核验;具体限制见交付清单。

Revisit consent button We value your privacy We use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking "Accept All", you consent to our use of cookies. Customise Reject All Accept All Customise Consent Preferences We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below. The cookies that are categorised as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more NecessaryAlways Active Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

Functional Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

Analytics Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

Performance Performance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.

Advertisement Advertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.

Uncategorised Other uncategorised cookies are those that are being analysed and have not been classified into a category as yet. No cookies to display. Reject All Save My Preferences Accept All Toggle SearchToggle Mobile Navigation Publish AI, ML & data-science insights to a global community of data professionals. Sign inSubmit an Article LatestEditor's PicksNewsletterShipAI


Write For TDS LinkedInXToggle Search Programming

Get Started with Rust: Installation and Your First CLI Tool – A Beginner’s Guide

From setup to your first command line application — step by step Niklas Lang May 13, 20257 min read Photo by David Valentine on Unsplash 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:

  1. 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.
  2. As soon as the download is complete, the rustup-init.exe file can be executed. A command line with various installation instructions then opens.
  3. Press the Enter key to run the standard installation to install Rust. This also includes the following tools:

After successful installation, Rust should automatically be available in your PATH. This can be easily checked in PowerShell or CMD using the following commands: Learn this step by step with the interactive Computer Science roadmap. bash

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:

  1. Open the terminal, for example, with the key combination Ctrl + Alt + T.
  2. To install Rust, the following command is executed:

bash

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
  1. 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.
  2. You may have to set the path manually. In this case, you can use this command, for example: bash
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: bash

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: bash

brew install rustup rustup-init

Alternatively, you can also install Rust directly using this script: bash

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: bash

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:

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:

bash

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: bash

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: rust

fn main() { 
     println!("Hello, Rust CLI-Tool!"); 
}

The program can be easily called up from the terminal using cargo: bash

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: bash

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:

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: bash

[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: bash

[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: bash

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: rust

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:

  1. Check arguments:
  2. Read the file:
  3. Parse JSON:
  4. Format output:

To test the tool, you can, for example, create a test file in the project directory under the name examples.json: 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: bash

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

Register Now to Continue Reading

Unlock Towards Data Science with a Free Account

All articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more. Register for freeSign in to your account


Written By

Niklas Lang

See all from Niklas Lang JsonProgrammingRustRust Cargo PackageSoftware Engineering Share This Article

Towards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program. Write for TDS

Related Articles

5 Development Rules to Improve Your Data Science Projects

Artificial Intelligence Simple tips to guide your data science workflow Lucas Soares September 20, 20216 min read

Foundational RL: Dynamic Programming

Machine Learning Road to Reinforcement Learning Rahul Bhadani December 19, 20225 min read

Battle of the Ensemble - Random Forest vs Gradient Boosting

Machine Learning Two of the most popular algorithms in the world of machine learning, who will win? Jason Chong June 2, 202110 min read

Two Functions to Know in Python

Artificial Intelligence Learn how to use the any() and all() functions in Python Luay Matalka February 19, 20215 min read

Announcing Feast 0.10 - Feast

Machine Learning Today, we're announcing Feast 0.10, an important milestone towards our vision for a lightweight feature store. Jay Parthasarthy April 15, 20218 min read

TDSP: When Agile Meets Data Science

Software Engineering A practical guide to applying agile principles to data science projects Amol Mavuduru January 23, 20237 min read

Writing Useful Functions to Explore Human Genetics with Python

Programming Simple Python Functions can help give an insight into Human Disease Stephen Fordham August 23, 20196 min read

Generate unedited Beatles lyrics using Markov Chain

Programming I love The Beatles so much, I wish they wrote more lyrics... wait, I'm a programmer, I can generate new lyrics based on their discography! Michele Riva May 2, 20212 min read

Analyzing Financial Data in Python

Programming Exploring Financial Data in Python Sadrach Pierre, Ph.D. July 19, 20219 min read

Your home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals. Subscribe to Our NewsletterWrite For TDS•About•Advertise•Privacy Policy•Terms of Use © Insight Media Group, LLC 2026•The New Stack•roadmap.sh•Creator Network

Recommended Articles

Close