Visualizing Rust Code Coverage in VS Code

Jirapat Klaokliang
3 min readMar 22, 2025

--

Hello Rustaceans! I am currently learning Rust and practicing writing unit tests with my favorite code editor, Visual Studio Code. When I write code in Go, it feels great to see the code coverage in the gutter alongside my code. and it can be done using just a few lines of configuration in Visual Studio Code. Well, I wanted the same feature in Rust too. After some research, I found a way to display code coverage in Rust as well. In this post, I will show you how to do it.

Before We Start

First, let’s create a new Rust project:

cargo new my-rust-project

Next, install nextest and cargo-llvm-cov using the following commands:

cargo install cargo-nextest --locked
cargo +stable install cargo-llvm-cov --locked

For Visual Studio Code, install the essential extensions:

Coding Time

Now, let’s write some code and tests. In this example, I will write a simple function that calculates student grades.

fn main() {
let score = 95;
let grade = calculate_grade(score);
println!("Score: {}, Grade: {}", score, grade);
}

pub fn calculate_grade(score: u32) -> &'static str {
match score {
90..=100 => "A",
80..=89 => "B",
70..=79 => "C",
60..=69 => "D",
0..=59 => "F",
_ => "Invalid Score",
}
}

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

#[test]
fn test_calculate_grade() {
assert_eq!(calculate_grade(95), "A");
assert_eq!(calculate_grade(85), "B");
assert_eq!(calculate_grade(75), "C");
assert_eq!(calculate_grade(65), "D");
assert_eq!(calculate_grade(50), "F");
}
}

Alright, we have written a simple function and a test for it. Now, let’s run the tests and show the report in CLI:

cargo llvm-cov nextest

If you want to see the coverage report in HTML format, just add the --open flag:

cargo llvm-cov nextest --open

Visual Studio Code Integration

First, you need to generate the coverage report in LCOV format using the following command:

cargo llvm-cov nextest --lcov --output-path ./target/lcov.info

Next, display the coverage from Coverage Gutters extension

Let’s see the result:

From the above image, you can see the code coverage in the gutter. The green lines are covered, and the red lines are not covered. Now, you can easily identify which lines are not covered by tests. Can you spot the missing test case?

Tip

If you want to update the coverage report automatically when you change the code, you can use the cargo watch command.

cargo watch -x 'llvm-cov nextest --lcov --output-path ./target/lcov.info' -w src

That’s it! Now you can see the code coverage in Visual Studio Code. I hope this post helps you to visualize code coverage in Rust. Happy coding!

Originally posted on nattrio.dev

Sign up to discover human stories that deepen your understanding of the world.

--

--

Jirapat Klaokliang
Jirapat Klaokliang

Written by Jirapat Klaokliang

Software Engineer | Logic & Wonder

No responses yet

Write a response