How to Install Rust on Ubuntu

Install Rust on Ubuntu

Rust is a modern systems programming language focused on safety, speed, and concurrency. First released in 2015 by Mozilla Research, Rust has quickly gained popularity among developers worldwide. The language is designed to provide memory safety without using garbage collection, making it ideal for performance-critical applications.

According to Stack Overflow’s Developer Survey, Rust has consistently ranked as the “most loved programming language” for several years running. This overwhelming developer satisfaction stems from Rust’s unique combination of low-level performance with high-level conveniences.

Rust offers numerous advantages that make it worth installing on your Ubuntu system:

  1. Memory Safety Without Garbage Collection: Rust’s ownership system ensures memory safety at compile time, preventing common bugs like null pointer dereferencing and buffer overflows without runtime overhead.
  2. Concurrency Without Fear: Rust’s type system and ownership model guarantee thread safety, eliminating data races at compile time.
  3. Zero-Cost Abstractions: Rust allows you to write high-level code without sacrificing performance. Abstractions compile down to efficient machine code similar to what you’d write by hand.
  4. Modern Tooling: Rust comes with Cargo, an integrated package manager and build system that makes dependency management, testing, and project organization straightforward.
  5. Cross-Platform Support: Rust supports numerous platforms, making it excellent for writing portable code that works across different operating systems.

Ubuntu provides an excellent environment for Rust development, with strong toolchain support and a Linux foundation that matches many deployment targets. Whether you’re building web servers, command-line tools, embedded systems, or performance-critical applications, Rust on Ubuntu offers a powerful development experience.

Prerequisites for Installing Rust on Ubuntu

System Requirements

Before installing Rust on your Ubuntu system, ensure you meet these basic requirements:

  • An Ubuntu system (any current version will work, but 18.04 LTS or newer is recommended)
  • At least 2GB of RAM (4GB+ recommended for comfortable development)
  • At least 1GB of free disk space
  • Administrator (sudo) access to your system
  • A working internet connection

Rust will run on virtually any Ubuntu configuration, including minimal server installations, desktop environments, and even within virtualized or containerized Ubuntu instances.

Required Dependencies

To ensure a smooth installation process, you’ll need to install several development tools and libraries. Open a terminal and run:

sudo apt update
sudo apt install build-essential curl wget libssl-dev pkg-config

This command installs:

  • build-essential: Provides the GCC compiler and related tools
  • curl: Used to download the Rust installer
  • wget: An alternative download tool
  • libssl-dev: Required for Rust’s SSL/TLS support
  • pkg-config: Helps find and use installed libraries

If you plan to work with specific libraries or features in Rust, you might need additional development packages. For instance, if you’ll be working with graphics libraries, you might need to install packages like libgtk-3-dev or libsdl2-dev.

Installation Methods Overview

Comparing Different Installation Approaches

There are three main ways to install Rust on Ubuntu, each with its own advantages and trade-offs:

  1. Rustup (Recommended): The official Rust toolchain installer and version manager. Rustup allows you to install and manage multiple Rust versions easily.
  2. Ubuntu Repositories: Installing Rust using Ubuntu’s package manager (apt). This method is simple but typically provides older Rust versions.
  3. Building from Source: Compiling Rust from its source code. This method offers the most control but requires more time and technical knowledge.

Here’s a comparison table to help you decide which method to use:

Method Pros Cons Best For
Rustup – Latest Rust versions
– Multiple toolchain management
– Cross-compilation support
– Easy updates
– Requires internet for installation Most users, professionals, learners
Ubuntu Repositories – Simple installation
– Integrated with system packages
– Older Rust versions
– Limited toolchain management
Quick testing, system integration
Source Build – Complete control
– Customization options
– Time-consuming
– Requires more expertise
Advanced users, custom requirements

For most users, the Rustup installation method provides the best balance of flexibility, ease of use, and access to up-to-date Rust versions. Let’s explore each method in detail.

Method 1: Installing Rust Using Rustup (Recommended)

What is Rustup?

Rustup is the official Rust toolchain installer and version manager developed by the Rust team. Think of it as the “nvm” for Node.js or “pyenv” for Python, but built specifically for Rust.

With Rustup, you can:

  • Install stable, beta, or nightly versions of Rust
  • Easily switch between different Rust versions
  • Add support for cross-compilation to different platforms
  • Update Rust components with a single command
  • Install additional components and tools

Rustup has become the de facto standard for installing Rust on all platforms. It ensures you get a consistent Rust setup with all the necessary tools like Cargo (Rust’s package manager), rustc (the compiler), and rustdoc (documentation generator).

Step-by-Step Rustup Installation

Follow these steps to install Rust using Rustup:

  1. Open a terminal window on your Ubuntu system.
  2. Download and run the Rustup installer by entering:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

This command downloads the Rustup installation script and pipes it directly to your shell for execution.

  1. Choose your installation type. You’ll be presented with installation options:
1) Proceed with installation (default)
2) Customize installation
3) Cancel installation

For most users, option 1 (the default) is recommended. If you have specific needs like installing to a different location, you can select option 2.

  1. Wait for the installation to complete. The installer will download and install the default toolchain (usually stable). This might take a few minutes depending on your internet connection.
  2. The installer will inform you when Rust has been installed and explain how to make the Rust commands available in your current shell.

Configuring Your Environment

After installation, you need to configure your shell to recognize Rust commands:

  1. Load Rust environment variables for your current shell session:
source $HOME/.cargo/env
  1. For permanent configuration, the installer should have already added the necessary lines to your ~/.profile or ~/.bash_profile. To verify this, you can check those files:
cat ~/.profile | grep cargo

You should see a line like:

export PATH="$HOME/.cargo/bin:$PATH"
  1. Log out and log back in, or restart your terminal to ensure the environment changes take effect.
  2. Verify your installation by checking the Rust version:
rustc --version

You should see output like:

rustc x.y.z (abcdefghi YYYY-MM-DD)

Where x.y.z is the version number, and YYYY-MM-DD is the release date.

  1. Verify Cargo installation as well:
cargo --version

With Rustup properly installed and configured, you now have access to the complete Rust toolchain, including the compiler, package manager, and documentation tools.

Method 2: Installing Rust from Ubuntu Repositories

Using APT Package Manager

If you prefer using Ubuntu’s package management system, you can install Rust directly from the official repositories. This method is simpler but provides an older Rust version:

  1. Update your package index:
sudo apt update
  1. Install Rust and Cargo:
sudo apt install rustc cargo
  1. Verify the installation:
rustc --version
cargo --version

The whole process typically takes less than a minute, making it the fastest installation method. The Rust version installed will depend on your Ubuntu version-newer Ubuntu releases generally include more recent Rust versions.

Limitations of Repository Installation

While installing from repositories is convenient, it comes with significant limitations:

  1. Older Rust versions: Ubuntu repositories often contain Rust versions that are several releases behind the current stable version. For example:
    • Ubuntu 20.04 LTS: Rust 1.41 (released February 2020)
    • Ubuntu 22.04 LTS: Rust 1.58 (released January 2022)

    Meanwhile, Rust releases new versions every six weeks, so repository versions can be many months or even years out of date.

  2. No toolchain management: You cannot easily switch between different Rust versions or channels (stable/beta/nightly).
  3. Limited components: Some Rust components or tools might not be included in the repository packages.
  4. Update limitations: You’ll only receive Rust updates when your Ubuntu system updates the package, not when new Rust versions are released.

Consider this method only if:

  • You need a quick Rust installation for basic exploration
  • You’re working on a project that specifically requires an older Rust version
  • You have strict system requirements that prevent using Rustup

For most development work, especially for new projects, the Rustup installation method provides a more complete and flexible solution.

Method 3: Building Rust from Source

When to Build from Source

Building Rust from source code is the most advanced installation method and is typically only necessary in specific situations:

  • You need to modify the Rust compiler itself
  • You’re developing for an unusual platform not supported by pre-built binaries
  • You need a custom build with specific configurations
  • You want to contribute to Rust development
  • You need to apply specific patches or customizations

This method requires more time, disk space, and technical knowledge than the other installation methods.

Compilation Process

If you need to build Rust from source, follow these steps:

  1. Install the required build dependencies:
sudo apt update
sudo apt install git gcc make curl libssl-dev pkg-config python3
  1. Clone the Rust repository:
git clone https://github.com/rust-lang/rust.git
cd rust
  1. Check out a specific version (optional, but recommended):
git checkout 1.69.0  # Replace with your desired version
  1. Create a configuration file:
cp config.toml.example config.toml

You may want to edit this file to customize your build. For a basic build, the default configuration is sufficient.

  1. Start the build process:
./x.py build

Be prepared to wait-building Rust from source can take anywhere from 30 minutes to several hours depending on your system’s specifications.

  1. Install Rust:
./x.py install

By default, this installs Rust to /usr/local. You can change the installation location by modifying the config.toml file before building.

  1. Verify your installation:
rustc --version
cargo --version

Building from source gives you complete control over your Rust installation, but it’s rarely necessary for most users. Unless you have specific requirements that can’t be met by Rustup or repository installations, the additional complexity is usually not justified.

Verifying Your Rust Installation

Testing Rust Compiler

Regardless of which installation method you chose, it’s important to verify that Rust is working correctly on your system:

  1. Check the Rust compiler version:
rustc --version

You should see output showing the version number, commit hash, and release date.

  1. Create a simple Rust program to test compilation:
echo 'fn main() { println!("Hello, Ubuntu Rust!"); }' > hello.rs
  1. Compile and run the program:
rustc hello.rs
./hello

You should see the output: Hello, Ubuntu Rust!

This confirms that the Rust compiler is correctly installed and able to produce executable programs on your Ubuntu system.

Testing Cargo Package Manager

Cargo is Rust’s package manager and build system. It’s essential for real-world Rust development, so you should verify it’s working properly:

  1. Check Cargo version:
cargo --version
  1. Create a new Rust project:
cargo new hello_cargo
cd hello_cargo
  1. Build and run the project:
cargo build
cargo run

You should see output like:

   Compiling hello_cargo v0.1.0 (/path/to/hello_cargo)
    Finished dev [unoptimized + debuginfo] target(s) in 0.56s
     Running `target/debug/hello_cargo`
Hello, world!
  1. Test Cargo’s dependency management by adding a simple dependency:

Add the following line to Cargo.toml under [dependencies]:

rand = "0.8"

Then modify src/main.rs to use this dependency:

use rand::Rng;

fn main() {
    let random_number = rand::thread_rng().gen_range(1..101);
    println!("Random number: {}", random_number);
}
  1. Build and run the updated project:
cargo build
cargo run

If Cargo successfully downloads and compiles the dependency, and your program runs and displays a random number, your Cargo installation is working correctly.

Managing Rust with Rustup

Installing Multiple Toolchains

One of Rustup’s most powerful features is its ability to manage multiple Rust toolchains. This lets you work with different Rust versions or release channels:

  1. View available toolchains:
rustup toolchain list
  1. Install additional toolchains:
rustup toolchain install nightly
rustup toolchain install beta
rustup toolchain install 1.65.0  # Install a specific version
  1. Set a default toolchain:
rustup default stable  # Or nightly, beta, etc.
  1. Use a non-default toolchain for a specific command:
rustup run nightly rustc --version
  1. Set a toolchain for a specific project by creating a rust-toolchain.toml file in your project directory:
[toolchain]
channel = "1.67.0"

This ensures everyone working on the project uses the same Rust version.

Updating Rust Components

Keeping your Rust installation up-to-date is simple with Rustup:

  1. Update all installed toolchains:
rustup update
  1. Check for available updates without installing them:
rustup check
  1. Update a specific toolchain:
rustup update stable
  1. Add additional components to your toolchain:
rustup component add rustfmt
rustup component add clippy

These are essential tools for formatting your code and catching common mistakes.

  1. Add cross-compilation targets:
rustup target add x86_64-pc-windows-gnu  # For Windows
rustup target add wasm32-unknown-unknown  # For WebAssembly

This allows you to compile Rust code for different platforms from your Ubuntu system.

Rustup makes it easy to maintain a complete and up-to-date Rust development environment, which is one of the main reasons it’s the recommended installation method.

Setting Up Your Development Environment

Recommended IDEs and Text Editors

To get the most out of Rust development on Ubuntu, you’ll want a good code editor or IDE with Rust support:

  1. Visual Studio Code (most popular):
    • Install from Ubuntu Software or download from the VS Code website
    • Add the “rust-analyzer” extension for intelligent code completion and analysis
    • Also install “Even Better TOML” for better Cargo.toml editing
    sudo snap install code --classic
  2. IntelliJ IDEA with Rust plugin:
    • Good choice if you’re coming from Java or other JetBrains IDEs
    • Install the Rust plugin from the JetBrains marketplace
    sudo snap install intellij-idea-community --classic
  3. Vim/Neovim:
    • Popular for terminal-based development
    • Use plugins like rust.vim and coc-rust-analyzer
    # For Vim
    sudo apt install vim
    # For Neovim
    sudo apt install neovim
  4. Sublime Text:
    • Lightweight editor with good Rust support via packages
    sudo snap install sublime-text --classic
  5. Emacs:
    • Install rust-mode and lsp-mode for Rust integration
    sudo apt install emacs

A 2022 Rust survey showed that VS Code is used by approximately 66% of Rust developers, making it the most popular choice by a significant margin. Whatever editor you choose, make sure it has support for:

  • Syntax highlighting for Rust
  • Code completion
  • Integration with Rustfmt (code formatter)
  • Integration with Clippy (linter)
  • Debugging support

Setting up a proper development environment will significantly improve your productivity and make learning Rust more enjoyable.

Common Installation Issues and Troubleshooting

Permission Problems

Some common permission-related issues you might encounter when installing or using Rust:

  1. Permission denied when running rustup or cargo commands:Solution: Never run rustup or cargo with sudo. Instead, fix the ownership of your Rust-related directories:
    sudo chown -R $(whoami):$(whoami) ~/.cargo ~/.rustup
  2. Can’t write to the installation directory:Solution: Ensure your user has write permissions to ~/.cargo and ~/.rustup:
    ls -la ~ | grep -E '\.cargo|\.rustup'

    If owned by root, reclaim ownership as shown above.

  3. Permission issues with global installations:Solution: For tools that need to be available system-wide, use proper PATH configuration rather than installing to system directories:
    # In /etc/profile.d/rust.sh
    export PATH="$PATH:/home/username/.cargo/bin"

Path Configuration Issues

Problems related to your PATH configuration can prevent Rust commands from being recognized:

  1. “Command not found” errors:Solution: Ensure Rust’s bin directory is in your PATH:
    echo $PATH | grep .cargo

    If not found, add it:

    echo 'export PATH="$HOME/.cargo/bin:$PATH"' >> ~/.bashrc
    source ~/.bashrc
  2. Changes to PATH not persisting:Solution: Make sure the PATH modification is in the right shell configuration file. For Bash, use ~/.bashrc; for Zsh, use ~/.zshrc:
    # For Bash
    echo 'export PATH="$HOME/.cargo/bin:$PATH"' >> ~/.bashrc
    
    # For Zsh
    echo 'export PATH="$HOME/.cargo/bin:$PATH"' >> ~/.zshrc
  3. Wrong version being used:Solution: Check which rustc is being executed:
    which rustc

    If it’s not from ~/.cargo/bin, your PATH order might be incorrect.

If you encounter more complex issues, the Rust community is very helpful. Check the official Rust forums or the Rust channel on Discord for assistance.

Creating Your First Rust Project

Using Cargo to Initialize Projects

Cargo makes it easy to create new Rust projects with the correct structure:

  1. Create a new binary application:
cargo new hello_world

This creates a new directory with a src/main.rs file containing a “Hello, world!” program.

  1. Create a library project if you’re building a reusable component:
cargo new --lib my_library

This creates a project with src/lib.rs instead of main.rs.

  1. Navigate to your project directory:
cd hello_world
  1. Build your project:
cargo build
  1. Run your project:
cargo run

You should see “Hello, world!” printed to the console.

Understanding Project Structure

A typical Rust project created by Cargo has the following structure:

project_name/
├── Cargo.toml       # Project metadata and dependencies
├── Cargo.lock       # Exact versions of dependencies (generated)
├── src/             # Source code directory
│   └── main.rs      # Entry point for binaries (or lib.rs for libraries)
└── target/          # Compiled outputs (generated)

The Cargo.toml file is the project manifest and contains:

[package]
name = "hello_world"
version = "0.1.0"
edition = "2021"

[dependencies]
# Add external dependencies here

To add a dependency, simply add it to the [dependencies] section:

[dependencies]
serde = "1.0"
reqwest = { version = "0.11", features = ["json"] }

After adding dependencies, run cargo build to download and compile them.

As your project grows, you might add:

  • More source files in src/ (Rust automatically detects modules)
  • A tests/ directory for integration tests
  • Examples in examples/
  • Benchmarks in benches/

Cargo handles the compilation details, allowing you to focus on writing code rather than managing build systems.

Keeping Rust Updated on Ubuntu

Update Methods and Best Practices

Maintaining an up-to-date Rust installation is important for security, performance improvements, and access to new language features:

  1. Regular updates with Rustup:
rustup update

Run this command monthly to get the latest stable Rust version. Rust typically releases a new stable version every six weeks.

  1. Check for updates without installing:
rustup check

This tells you if updates are available without making any changes.

  1. Update specific components:
rustup component add rustfmt clippy

Make sure to keep these code quality tools updated.

  1. Update Cargo tools:

To update tools installed via Cargo, you can use cargo-update:

cargo install cargo-update
cargo install-update -a  # Updates all installed tools
  1. Create an update schedule:

Best practices include:

  • Setting calendar reminders to update monthly
  • Checking the official Rust blog for important updates
  • Having a test project to verify everything works after updates
  • Pinning versions in critical production projects to ensure stability

Keeping Rust updated ensures you have access to the latest optimizations, features, and security fixes. However, for production projects, it’s wise to test updates thoroughly before deploying.

Uninstalling Rust

Complete Removal Steps

If you need to remove Rust from your Ubuntu system, the process depends on how you installed it:

  1. If installed via Rustup:
rustup self uninstall

This command will remove Rustup and all installed toolchains. It will ask for confirmation before proceeding.

  1. If installed via apt:
sudo apt remove --purge rustc cargo
sudo apt autoremove
  1. If installed from source:

If you compiled Rust from source, removal depends on how you installed it. Typically:

sudo rm -rf /usr/local/lib/rustlib
sudo rm -rf /usr/local/bin/rustc
sudo rm -rf /usr/local/bin/cargo

Adjust the paths if you installed to a different location.

  1. Cleaning up environment variables:

Check your shell configuration files (~/.bashrc, ~/.profile, etc.) and remove any Rust-related PATH additions or environment variables.

  1. Removing Rust projects and caches:
rm -rf ~/.cargo  # Removes Cargo's cache and configuration
rm -rf ~/.rustup  # Removes Rustup data if not already removed

After completing these steps, Rust should be completely removed from your system. If you decide to reinstall later, you can follow the installation instructions again.

Frequently Asked Questions

1. How often should I update my Rust installation on Ubuntu?

Rust releases a new stable version approximately every six weeks. It’s recommended to update your installation monthly using rustup update to ensure you have the latest features, performance improvements, and security fixes. For production environments, consider testing updates in a development environment first to ensure compatibility with your codebase.

2. Can I have multiple versions of Rust installed simultaneously on Ubuntu?

Yes, this is one of the primary benefits of using Rustup for installation. You can install multiple toolchains (e.g., stable, beta, nightly, or specific versions) and switch between them as needed. Use rustup toolchain install to add versions and rustup default or rustup override to switch between them. This is particularly useful when working on multiple projects with different version requirements.

3. Is Rust suitable for beginners learning programming on Ubuntu?

While Rust has a steeper learning curve than some languages, it can be an excellent choice for dedicated beginners, especially those interested in systems programming. Ubuntu provides a great environment for learning Rust, with strong tooling support and a Unix-like system that matches many deployment targets. The Rust documentation, including “The Book” (accessible via rustup doc --book), is exceptionally well-written and beginner-friendly.

4. How do I install additional Rust components like rustfmt and clippy?

You can install additional components using Rustup’s component management:

rustup component add rustfmt  # Code formatter
rustup component add clippy   # Linter with additional checks
rustup component add rust-src # Source code for the standard library
rustup component add rust-analyzer # Language server for IDE integration

These tools are essential for maintaining code quality and following Rust best practices.

5. Can I use Rust for web development on Ubuntu?

Absolutely! Rust has a growing ecosystem for web development. You can build high-performance web servers using frameworks like Actix Web, Rocket, or Warp. For frontend development, Rust can compile to WebAssembly (WASM), allowing you to write performant browser-based applications. To add WebAssembly support to your Rust installation on Ubuntu, run:

rustup target add wasm32-unknown-unknown
cargo install wasm-pack

This enables you to compile Rust code to WASM and integrate it with JavaScript frameworks.

Marshall Anthony is a professional Linux DevOps writer with a passion for technology and innovation. With over 8 years of experience in the industry, he has become a go-to expert for anyone looking to learn more about Linux.

Related Posts