Rust CI/CD: a practical introduction

From the series Rust CI from first principles, part 1 of 3

Reading time
10 min
Level
Beginner
Prerequisites
Basic Rust and Cargo

Rust gives developers an unusually powerful set of tools for writing reliable software: its compiler catches entire categories of mistakes before code ever runs, its ownership system helps prevent memory-safety bugs, and tools like Clippy help maintain high standards across a codebase.

But even with Rust’s guarantees, software development involves more than writing code that compiles. We need to know that our tests pass, changes haven’t broken anything, and every contribution meets the same quality standards.

Continuous integration (CI) is about collecting evidence that your code meets the standards you set and behaves as you expect, so you can integrate changes with confidence. A well-designed Rust CI pipeline brings together the compiler, Clippy, automated tests, and other checks to provide consistent feedback on every change.

In this article, we’ll explore what CI/CD means for Rust projects, introduce the essential Cargo commands, and build a working CI pipeline using GitHub Actions. We’ll also look at what these checks actually guarantee and why running them can sometimes be surprisingly expensive.

1. What is CI/CD?

CI/CD stands for continuous integration and continuous delivery or deployment. Although the terms are often used together, they describe different parts of the software development process.

Continuous integration

Continuous integration (CI) is the practice of regularly integrating code changes into a codebase and automatically verifying those changes.

Imagine you’re working on a Rust application with several other developers. One developer modifies an API, another updates a dependency, and a third introduces a new feature.

Each change might work perfectly on its author’s machine. But that doesn’t necessarily mean it will work when combined with everyone else’s changes. A CI system helps address this problem. Whenever someone opens a pull request or pushes a commit, the system can automatically:

  1. Download the latest source code.
  2. Prepare the development environment.
  3. Check that the code compiles.
  4. Run linters and formatting checks.
  5. Execute automated tests.
  6. Report whether the checks succeeded.

If something fails, developers receive feedback before the change is merged.

  1. Developer pushes code
  2. CI workflow starts
  3. Prepare environment
  4. Format, check, lint and test

All checks pass?

Yes

Ready for review and merge.

No

Report failures. The developer fixes problems and pushes code again, restarting the workflow.

CI reports a result for each change; fixes start the feedback loop again.

CI doesn’t replace code review or good engineering practices. Instead, it automates checks that would otherwise need to be performed manually.

Continuous delivery and deployment

Continuous delivery extends CI by ensuring that software can be released reliably. A delivery pipeline might build a production executable, package it into a container, or prepare a release artifact. Continuous deployment takes this a step further by automatically deploying successful changes to a production environment.

Not every Rust project needs deployment. A command-line tool might publish releases to GitHub. A library might publish new versions to crates.io. A backend service might deploy containers to a production cluster.

The specific delivery process depends on the application. For now, we’ll focus primarily on continuous integration: establishing that a change satisfies the project’s automated quality checks before it is merged.

2. Why Rust and CI work so well together

One of Rust’s greatest strengths is how much work its compiler performs on our behalf. In many programming languages, entire categories of errors remain undetected until a program executes. Rust takes a different approach. Its type system and ownership model allow the compiler to reject many problematic programs before they’re run.

For example, consider this code:

fn main() {
    let message = String::from("Hello, Rust!");

    let other = message;

    println!("{message}");
}

This program doesn’t compile. The ownership of message has been moved into other, so attempting to use message afterwards is an error. Rust detects that problem statically.

In safe Rust, the compiler also enforces rules that prevent many forms of memory unsafety, including use-after-free errors and data races. These are powerful guarantees, particularly for systems programming.

Of course, Rust isn’t magic. Programs can still contain incorrect business logic, deadlocks, resource leaks, and other defects. Unsafe code also requires additional care. Nevertheless, Rust’s compiler provides an exceptional foundation for reliable software.

And it doesn’t stop there. Rust also has Clippy, a collection of additional lints that can identify suspicious code, potential mistakes, and non-idiomatic patterns. Combined with automated tests, these tools provide several complementary layers of verification.

The real opportunity with CI is to apply those layers consistently. Instead of relying on every developer to remember which commands to run, we can make them an automatic part of the development process.

3. The essential Rust CI tools

Most Rust CI pipelines are built around a handful of familiar Cargo commands. If you’ve already been developing in Rust, you’ll probably recognize most of them. What matters is understanding what each command contributes.

Formatting: cargo fmt

cargo fmt --all -- --check

Rust comes with rustfmt, which automatically formats code according to consistent conventions. The command above checks whether all workspace members are correctly formatted. The --check option is important: rather than modifying files, it reports whether any formatting changes would be required. This makes it suitable for CI.

Formatting might seem relatively unimportant compared with testing, but consistent formatting removes a surprising amount of friction from collaborative development. Developers don’t need to debate indentation, spacing, or the layout of expressions. The formatter handles those decisions.

Compilation checking: cargo check

cargo check --workspace

cargo check asks Cargo to check whether the selected Rust packages compile without producing their normal final executable artifacts. It runs compiler analysis, including type checking and borrow checking, while generally avoiding machine-code generation for the crates being checked. This can make it substantially faster than a full build.

There is an important nuance: build scripts and procedural macros may still need to be compiled into executable code. For a developer editing Rust code, cargo check is often one of the fastest ways to get useful compiler feedback. In CI, it provides an explicit compilation-checking step.

Static analysis: cargo clippy

cargo clippy --workspace --all-targets

Clippy is one of our favourite parts of the Rust ecosystem. The Rust compiler is already exceptionally good at enforcing the language’s rules. Clippy builds on that foundation with additional analysis. It includes lints for correctness problems, suspicious patterns, unnecessary complexity, and performance-related issues.

Let’s look at a simple example. Suppose we’re writing a function that checks whether two values are equal:

fn is_duplicate(left: u32, right: u32) -> bool {
    left == left
}

This is valid Rust. But we’ve accidentally compared left with itself rather than comparing it with right. The comparison will always return true.

Clippy’s eq_op lint identifies comparisons involving identical operands, which are frequently the result of typing or copy-and-paste mistakes. The correct implementation is:

fn is_duplicate(left: u32, right: u32) -> bool {
    left == right
}

That’s a simple example, but it illustrates an important point. Code can compile successfully and still contain mistakes that static analysis can help identify. Clippy’s lint collection contains many such checks, ranging from clear correctness problems to suggestions for writing more idiomatic Rust.

Making Clippy part of CI

Normally, some compiler and Clippy warnings don’t cause the command to fail. In CI, we often want stricter behaviour. One widely supported approach is:

cargo clippy --workspace --all-targets -- -D warnings

The -D warnings argument treats warnings as errors. This means warnings detected by Clippy or rustc can cause the CI job to fail. Recent Cargo versions also support configuring this behaviour through build.warnings = "deny" or the CARGO_BUILD_WARNINGS=deny environment variable.

Clippy is particularly valuable because it catches issues that might otherwise escape notice during code review. It isn’t a substitute for tests, but it complements them extremely well.

Testing: cargo test

cargo test --workspace

Rust has excellent built-in support for automated testing. Unit tests can live alongside application code:

pub fn add(a: i32, b: i32) -> i32 {
    a + b
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn adds_two_numbers() {
        assert_eq!(add(2, 3), 5);
    }
}

Running cargo test compiles the relevant test targets and executes the tests. If an assertion fails, the command reports a failure. Cargo also supports integration tests, documentation tests, and different test configurations. The precise set of tests executed depends on the selected packages, targets, and command options.

Tests are important because compilation alone cannot establish that a program behaves as intended. The compiler can verify that a function accepts and returns the correct types. It generally cannot determine whether the function implements the business requirements you had in mind. Tests give us a way to verify specific behaviours.

Building: cargo build

cargo build --workspace

Finally, cargo build compiles the selected packages and produces their normal build outputs. Unlike cargo check, it performs the code-generation work needed to produce compiled artifacts.

By default, Cargo uses the development profile. For an optimized release build, we can run:

cargo build --workspace --release

Release builds can be significantly more expensive because optimization settings are different.

Do we always need both cargo check and cargo build in CI?

Not necessarily. Some commands perform overlapping work. For example, cargo test already compiles the code required for its test targets. A separate build step is useful when we specifically want to verify or produce the application’s normal build artifacts.

Understanding which commands perform overlapping work becomes important when optimizing CI. We’ll explore that in detail in the next article.

4. Building your first Rust CI pipeline

Now that we understand the tools, let’s put them together. We’ll use GitHub Actions, although the same principles apply to other CI providers.

GitHub Actions executes workflows defined in YAML files stored in a repository. For this example, we’ll assume you have a Rust project hosted on GitHub and a committed Cargo.lock file.

Create the workflow

Create a file at:

.github/workflows/rust-ci.yml

Add the following:

name: Rust CI

on:
  push:
    branches: [main]
  pull_request:

permissions:
  contents: read

env:
  RUSTUP_TOOLCHAIN: '1.97.1'

jobs:
  rust-ci:
    name: Check, lint and test
    runs-on: ubuntu-24.04

    steps:
      - name: Check out source
        uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
        with:
          persist-credentials: false

      - name: Install Rust toolchain
        uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec
        with:
          toolchain: '1.97.1'
          components: clippy, rustfmt

      - name: Check formatting
        run: cargo fmt --all -- --check

      - name: Check compilation
        run: cargo check --workspace --all-targets --locked

      - name: Run Clippy
        run: cargo clippy --workspace --all-targets --locked -- -D warnings

      - name: Run tests
        run: cargo test --workspace --locked

      - name: Build
        run: cargo build --workspace --locked

This is a complete starting point for a conventional Rust workspace using the default feature configuration. The checkout and Rust-toolchain actions follow their documented setup patterns.

Understanding the workflow

Let’s walk through what happens. First, GitHub detects a change. Our configuration runs on pull requests and pushes to the main branch.

Second, GitHub prepares a runner. The runner is the machine that executes our workflow. For this example, we’re using an Ubuntu-based GitHub-hosted runner.

Third, the workflow checks out the repository. The runner needs access to the source code before it can compile or test anything.

Fourth, it installs Rust. We’ve pinned Rust 1.97.1 and requested the Clippy and rustfmt components.

The Rust version and action revisions are pinned so updates are deliberate. Use the same Rust version locally, and change both toolchain values when upgrading. RUSTUP_TOOLCHAIN keeps a repository override from selecting a different version.

Finally, it runs our checks. Formatting, compilation checking, linting, testing, and building run in sequence.

If a step fails, GitHub Actions normally stops executing subsequent steps in that job and reports the failure. We can then inspect the logs to understand what happened. And that’s it: we now have a functioning Rust CI pipeline.

A note about the example

Real projects often need more configuration. Some require PostgreSQL or other external services. Others compile for multiple operating systems or architectures.

Projects with optional features may need to test several feature combinations. For example:

cargo test --workspace --all-features

This activates all available features for the selected packages, which is useful when those features are compatible with one another. However, not every project supports every feature simultaneously.

The workflow should reflect the configurations your project actually promises to support. --all-targets selects Cargo targets such as tests and examples, not every operating system or CPU architecture. The key is to begin with a small, reliable pipeline and expand it as requirements become clearer.

5. What does passing CI actually guarantee?

At this point, we have several automated checks. But what does it really mean when they all pass? This is worth understanding because different checks establish different properties.

The compiler

Successful compilation tells us that our code satisfies the Rust language rules checked by the compiler for that particular configuration. This includes an exceptionally valuable collection of type, ownership, borrowing, and safety checks. For safe Rust code, these rules prevent important classes of memory-safety defects. But compilation doesn’t establish that every function implements its intended behaviour.

Clippy

Clippy performs additional static analysis. It can identify suspicious code, potential mistakes, and patterns worth improving.

However, it cannot detect every possible bug. And not every Clippy warning indicates incorrect behaviour. Some relate to style, maintainability, or performance.

Automated tests

Tests verify particular behaviours under particular conditions. If a test passes, we know that its assertions succeeded for that execution. But passing tests don’t necessarily cover every possible input, external dependency, or execution scenario.

Putting the guarantees together

The value of Rust CI comes from combining these layers. The compiler enforces important language guarantees. Clippy provides additional analysis. Tests verify selected behaviours.

And CI ensures that the configured checks run consistently as code changes. This doesn’t make bugs impossible. It gives us a powerful, repeatable process for detecting problems early and preventing known failures from being merged. For us, that’s one of the most compelling aspects of developing with Rust.

6. Why can Rust CI be slow?

There’s an interesting consequence of everything we’ve discussed. A Rust CI pipeline can perform a substantial amount of work. The compiler isn’t simply translating source code into machine instructions. It performs sophisticated analysis, processes dependencies, expands macros, checks types and borrowing rules, and, when required, generates machine code.

Tests introduce additional compilation and execution work. And because our workflow runs several Cargo commands, some compilation work may be shared while other work must be performed separately.

The situation becomes more interesting when we consider caching. When you build a project locally, Cargo may already have compatible compilation artifacts from previous builds. But a CI runner may begin without those artifacts. This distinction between a cold build and a warm build can have a major effect on performance.

Even when caching is enabled, changes to dependencies, compiler versions, features, or compilation settings may prevent previous artifacts from being reused. None of this means Rust’s tooling is poorly designed. Many of these costs are associated with doing the sophisticated compilation and verification work that makes Rust so attractive.

But as Rust projects grow, understanding and managing these costs becomes increasingly important. We’ll investigate them properly later in this series.

7. Practical advice for reliable Rust CI

Before wrapping up, here are a few practices worth adopting as your Rust project grows.

Keep your dependencies predictable

Cargo uses Cargo.lock to record the resolved dependency versions of a project. For applications, committing this file is generally recommended. In our workflow, we’ve used --locked:

cargo test --workspace --locked

This tells Cargo to fail rather than modify the lockfile or resolve dependencies differently. It requires an existing, up-to-date Cargo.lock. For libraries, dependency-testing policies can differ, but using a committed lockfile is still a reasonable choice for reproducible CI runs.

Use a consistent Rust toolchain

Rust evolves regularly, and new compiler or Clippy versions can introduce changes in diagnostics and lint behaviour. A project that passes on one toolchain version might produce different warnings or encounter compatibility issues on another. Using a consistent toolchain helps make failures easier to understand. For projects requiring stricter reproducibility, pin the Rust version rather than following the moving stable release.

Think about the configurations you support

Rust’s feature system is powerful, but it also means a crate can behave differently under different feature combinations. Similarly, code may compile on Linux but fail on Windows or macOS.

Your CI configuration should reflect the configurations your users depend on. That doesn’t necessarily mean checking every theoretically possible combination. It means making deliberate decisions about what you test.

Keep the pipeline understandable

It’s tempting to add sophisticated caching, parallel execution, and numerous third-party actions immediately. Sometimes those optimizations are justified. But a complicated CI system introduces its own maintenance burden.

For a new project, a simple pipeline that provides reliable feedback is usually a better starting point. Once you’ve established how long your checks take and where the time goes, you can make informed optimization decisions.

8. Where do we go from here?

We’ve now covered the fundamentals of Rust continuous integration. We know what CI is, why Rust’s tooling makes it particularly valuable, and how to configure an automated pipeline using GitHub Actions. We’ve also introduced five important commands:

  • cargo fmt
  • cargo check
  • cargo clippy
  • cargo test
  • cargo build

But we’ve only scratched the surface of what happens when we execute them. For example, when you run cargo check, how does Cargo decide which dependencies need to be compiled? Does cargo test perform the same compilation work as cargo build? And why can changing a seemingly insignificant line of code sometimes trigger substantial recompilation?

These questions lead us into the internal workings of Cargo and the Rust compiler. In the next article, What actually happens during Rust CI?, we’ll follow a CI run from source checkout through dependency resolution, compilation, and test execution. We’ll examine the different responsibilities of Cargo and rustc, how they coordinate compilation, and why understanding their behaviour is essential to building faster Rust CI systems.

Rust’s compiler is one of its greatest strengths. Understanding how it works is the first step toward making the most of it.

Rust CI from first principles is an educational series by Sorus, exploring Rust compilation, testing, continuous integration, and developer productivity.

Further reading