Compile Warnings vs Errors in an Axum Project
Learn how to read and respond to compiler warnings and errors when building an Axum web application with Rust and Cargo.
When you write code for an Axum project in Rust, you will constantly see messages from the compiler. Some messages say warning:, others say error:. Understanding the difference between these two kinds of messages is one of the most important skills for keeping your project clean and moving forward.
This page explains what warnings and errors are, why they happen, how to read the messages Cargo prints, and how to fix the most common ones you will meet while building your first Axum application. We will use simple examples from a typical src/main.rs file so everything stays concrete.
What the Compiler and Cargo Do
Before looking at warnings and errors, you need a basic mental picture of what happens when you run a command like cargo run or cargo build.
Rust is a compiled language. That means the code you write in a .rs file is not something the computer can run directly. First, a program called the compiler reads your Rust source code, checks it for mistakes, and translates it into machine code the computer understands.
Cargo is a build tool and package manager for Rust. When you type cargo run, Cargo takes care of several steps:
- It reads your
Cargo.tomlto understand your project's dependencies. - It downloads and compiles any libraries you depend on, like
axumandtokio. - It runs the Rust compiler on your own source files.
- If the compiler succeeds, Cargo runs the resulting executable.
During step 3, the compiler can produce two kinds of messages: warnings and errors. Both appear in the terminal, but they mean very different things for your project.
Compiler as a proofreader:
Think of the compiler as a strict proofreader reading your essay before you submit it. A warning is like a comment in the margin: "You used this word but never defined it," or "This paragraph seems unused." An error is like a spelling mistake that makes the whole sentence impossible to understand. The proofreader cannot accept the essay if there are errors, but warnings can be ignored - though that is usually a bad idea.
Compile Warnings: What They Look Like and Why They Appear
A warning is a message from the compiler that says, "Your code is technically valid, but something looks suspicious or unnecessary." Warnings do not stop the compiler from producing a working program. Your code will still compile and run.
Warnings exist because Rust's developers want to help you catch potential bugs before they become real problems. The compiler notices patterns that often indicate mistakes, even if the code is technically allowed by the language rules.
Common Warning Examples in an Axum Project
Let's start with a very small Axum src/main.rs that produces a warning.
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(hello));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
let unused_variable = 42;
axum::serve(listener, app).await.unwrap();
}
async fn hello() -> &'static str {
"Hello, world!"
}
If you save this file and run cargo check (a fast way to compile without producing a final executable), you will see output similar to this:
warning: unused variable: `unused_variable`
--> src/main.rs:9:9
|
9 | let unused_variable = 42;
| ^^^^^^^^^^^^^^^ help: if this is intentional, prefix it with an underscore: `_unused_variable`
|
= note: `#[warn(unused_variables)]` (part of `#[warn(unused)]`) on by default
This warning tells you that you created a variable named unused_variable and assigned it the value 42, but you never used it afterwards. The compiler is not saying your code is broken - it is saying, "Did you mean to use this? If not, you can remove it." The warning also gives a concrete suggestion: prefix the variable name with an underscore (_unused_variable) to tell the compiler that you know it is unused and you want to keep it for some reason.
Other warnings you might see early on include:
- unused import - you brought a name into scope with
usebut never used it. - unused
mut- you declared a variable as mutable withlet mut, but you never change its value. - dead code - you defined a function or struct that is never called or constructed.
- deprecated - you used a feature that the library authors have marked as outdated.
Each warning includes a helpful message and usually a suggestion on how to fix it.
How to Read a Warning Message
A typical warning message from Rust has a consistent format. Let's break down the one above piece by piece:
warning:- the kind of message.unused variable: \unused_variable`` - a short description of the problem.--> src/main.rs:9:9- the file, line number, and column where the problem was found.- The code snippet with a pointer (
^^^^) shows exactly what part of the line is involved. help:- a concrete suggestion for fixing the issue.= note:- extra information, such as which lint rule produced the warning.
You do not need to memorize every field. The important parts are the description and the help: line. Most of the time, the suggestion will fix the warning correctly.
Warnings mean progress:
Seeing a warning does not mean you failed. It means the compiler found something worth a second look. Fixing warnings as you go keeps your project healthy and prevents small oversights from turning into larger problems later.
Compile Errors: What They Look Like and Why They Appear
An error is a message that says, "Your code is invalid and cannot be turned into a working program." Errors stop the compilation process completely. If there is even one error, Cargo will not produce a binary, and cargo run will refuse to run your program.
Errors come from many sources: typos, missing symbols, type mismatches, broken syntax, and attempts to use features that don't exist.
Common Error Examples in an Axum Project
One of the most frequent errors for Axum beginners is using a normal synchronous function as a handler. Axum requires handlers to be async fn because the web framework runs on an asynchronous runtime.
Here is a small program with that mistake:
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(hello));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
fn hello() -> &'static str {
"Hello, world!"
}
If you run cargo check on this code, you will see something like:
error[E0277]: the trait bound `fn() -> &'static str {hello}: Handler<_, _>` is not satisfied
--> src/main.rs:5:25
|
5 | .route("/", get(hello));
| --- ^^^^^ the trait `Handler<_, _>` is not implemented for fn item `fn() -> &'static str {hello}`
| |
| required by a bound introduced by this call
|
= note: Consider using `#[axum::debug_handler]` to improve the error message
note: required by a bound in `axum::routing::get`
= note: this error originates in the macro `top_level_handler_fn` (in Nightly builds, run with -Z macro-backtrace for more info)
This error message says that the function hello does not implement the Handler trait, which Axum requires for anything passed to get. The root cause is that hello is a regular function, not an async function.
The fix is to add the async keyword before fn:
async fn hello() -> &'static str {
"Hello, world!"
}
Another common error is forgetting to import a necessary item. Suppose you write:
use axum::Router;
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(hello));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
async fn hello() -> &'static str {
"Hello, world!"
}
You forgot use axum::routing::get;. The compiler will complain:
error[E0425]: cannot find function `get` in this scope
--> src/main.rs:5:21
|
5 | .route("/", get(hello));
| ^^^ not found in this scope
The error message tells you what is missing. The fix is to add the import at the top of the file, as shown in the Missing Import walkthrough below.
How to Read an Error Message
Error messages are usually longer and more detailed than warnings, but they follow a similar structure:
error[E####]- the worderror, followed by a Rust error code in brackets. The code helps you search for more information online if you get stuck.- The description, file location, and code snippet.
help:lines that tell you how to fix the issue.note:lines that explain the chain of type requirements or trait bounds.
The most important skill is to read the help: lines first. They often contain the exact solution. If the help is not enough, search for the error code (like E0277) along with your framework name; you will usually find explanations from other developers who hit the same problem.
Errors block everything:
Unlike warnings, errors prevent your program from building. You cannot run or test your code until you fix every error. This might feel frustrating, but it is also helpful: the compiler catches mistakes early, before they become runtime crashes or security holes.
How Cargo Tells the Difference: Output Format and Exit Behavior
When you run cargo check, cargo build, or cargo run, Cargo prints messages from the compiler to your terminal. Warnings and errors look different visually:
- Warnings are prefixed with
warning:and are usually shown in yellow (if your terminal supports colors). - Errors are prefixed with
error:orerror[E####]and are shown in red.
More importantly, Cargo behaves differently after compilation:
- If there are only warnings, Cargo prints them and then continues. The final executable is produced (for
cargo buildorcargo run). You will see a line likeFinished dev [unoptimized + debuginfo] target(s) in 1.23s. Your program runs normally. - If there are any errors, Cargo stops and does not produce an executable. You will see a summary like
error: could not compile \my-axum-app` (bin "my-axum-app") due to 1 previous error`.
Understanding this difference is crucial: warnings are advisory, errors are blocking.
Fixing Warnings: Practical Walkthroughs
Now let's look at the most common warnings you will meet in a beginner Axum project and how to fix them correctly.
Unused Variable
You saw this earlier:
let unused_variable = 42;
The compiler warns that you never use unused_variable. There are two acceptable fixes:
Option 1: Remove the line entirely. If you really don't need the variable, the cleanest fix is to delete it.
// no line at all
Option 2: Prefix with an underscore. If you want to keep the variable for documentation or future use, rename it so it starts with _. The compiler understands that _something means "intentionally unused."
let _unused_variable = 42;
Both fixes remove the warning. Choosing between them depends on whether the variable has any purpose in your code. If it is just leftover from an experiment, delete it. If it holds a value you plan to use later, keep it with the underscore.
Unused Import
Suppose you added an import you thought you needed:
use axum::Json;
use axum::{routing::get, Router};
You never actually use Json in your handlers. The compiler warns:
warning: unused import: `axum::Json`
--> src/main.rs:1:5
|
1 | use axum::Json;
| ^^^^^^^^^^
|
= note: `#[warn(unused_imports)]` (part of `#[warn(unused)]`) on by default
The fix is simple: delete the unused import line. In many code editors, you can automatically remove unused imports with a keyboard shortcut or a save-time formatter.
Unused mut
If you write let mut response = String::new(); but never call a method that mutates response, the compiler will warn:
warning: variable does not need to be mutable
--> src/main.rs:10:9
|
10 | let mut response = String::new();
| ----^^^^^^^^
| |
| help: remove this `mut`
The fix is to remove the mut keyword:
let response = String::new();
Dead Code
If you define a function that is never called, the compiler warns that it is dead code:
async fn unused_handler() -> &'static str {
"I am never called"
}
The warning looks like:
warning: function `unused_handler` is never used
--> src/main.rs:11:10
|
11 | async fn unused_handler() -> &'static str {
| ^^^^^^^^^^^^^^
|
= note: `#[warn(dead_code)]` (part of `#[warn(unused)]`) on by default
If you really do not need the function, delete it. If you are planning to use it later, you can add #[allow(dead_code)] above the function to silence the warning temporarily:
#[allow(dead_code)]
async fn unused_handler() -> &'static str {
"I am never called"
}
However, the better long-term solution is to actually wire the function into your router, if that is your goal.
Don't silence warnings blindly:
Adding #[allow(...)] or using underscore prefixes is fine when you have a good reason, but do not let warnings accumulate without thought. A warning often points to a real oversight - like a handler you forgot to route or a variable you meant to use in a calculation. Always ask yourself why the warning appeared before suppressing it.
Fixing Errors: Practical Walkthroughs
Unlike warnings, errors must be fixed. Here are three errors you will almost certainly meet early on, with step-by-step fixes.
Error: Handler Must Be Async
We already saw this error. The mistake is defining a handler without the async keyword. The full corrected src/main.rs looks like this:
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(hello));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
async fn hello() -> &'static str {
"Hello, world!"
}
The only change is adding async before fn hello. After that, hello implements the Handler trait and the route registration works.
Error: Missing Import
If you forget use axum::routing::get;, the compiler will say cannot find function \get` in this scope`. The fix is to add the import at the top of the file:
use axum::{routing::get, Router};
Now get is in scope and the compiler can find it.
Error: Type Mismatch
Suppose you try to return a String from a handler that is declared to return &'static str:
async fn hello() -> &'static str {
String::from("Hello, world!")
}
The compiler will complain:
error[E0308]: mismatched types
--> src/main.rs:9:5
|
8 | async fn hello() -> &'static str {
| ------------ expected `&'static str` because of return type
9 | String::from("Hello, world!")
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `&str`, found `String`
|
help: consider borrowing here
|
9 | &String::from("Hello, world!")
| +
The problem is that String and &str are different types. The easiest fix is to return a string slice instead:
async fn hello() -> &'static str {
"Hello, world!"
}
If you need to build a dynamic string, you can change the return type to String:
async fn hello() -> String {
format!("Hello, {}!", "world")
}
Axum accepts both String and &str as response types because both implement IntoResponse. So the choice depends on what you are doing. The key is to make sure the declared return type matches the actual value you return.
Using cargo check for Fast Feedback
When you are learning, it is tempting to always use cargo run to test your program. But cargo run compiles the whole project, links it, and then runs the server - which can take a while, especially as your project grows.
cargo check is a faster command. It performs most of the compiler's analysis (checking for warnings and errors) but does not produce a final executable or run it. This means you get feedback about warnings and errors in a fraction of the time.
Here is how to use it during development:
cargo check
You will see the same warnings and errors as with cargo build, but without the extra steps of linking and running. Many developers run cargo check after every small code change, then run cargo run only when they want to actually test the server.
Fast feedback loop:
The faster you can see compiler messages, the sooner you can fix problems. cargo check is your best friend for staying aware of warnings and errors without waiting for a full build.
Treating Warnings as Errors: deny(warnings)
For a clean, professional project, you might decide that no warnings are acceptable. Rust lets you turn warnings into hard errors by adding a special attribute at the top of your src/main.rs:
#![deny(warnings)]
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(hello));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
async fn hello() -> &'static str {
"Hello, world!"
}
With #![deny(warnings)], any warning will cause the compilation to fail, just like a regular error. This forces everyone working on the project to keep the code warning-free.
There is also #![forbid(warnings)], which does the same thing but cannot be overridden locally with #[allow]. That level of strictness is often overkill for beginners, but deny(warnings) can be a useful habit as you build larger projects.
If you decide to use deny(warnings), remember to fix every warning as soon as it appears. Otherwise, you will find yourself blocked by what used to be just a harmless message.
Extra Linting with Clippy
Rust ships with a separate tool called Clippy that provides additional, more opinionated warnings called lints. Clippy catches things the standard compiler does not, such as overly complex expressions, style inconsistencies, and potential performance issues.
You can run Clippy with:
cargo clippy
Clippy produces messages that look like compiler warnings, but they are prefixed with warning: and often have a clippy:: label. For example, if you write if x == true { ... }, Clippy will suggest writing if x { ... } instead.
Clippy is not required for Axum projects, but it is a powerful tool for keeping your code clean and catching subtle bugs. Treat Clippy warnings the same way you treat compiler warnings: understand why they appear, fix them if they point to a real issue, and suppress them only with a good reason.
Common Beginner Mistakes and How to Avoid Them
When you first start reading compiler messages, a few habits can trip you up.
Ignoring warnings because "the program runs"
A warning does not stop your program from running, so it is easy to ignore. But warnings often reveal real bugs: an unused variable might be a line you meant to use; an unused import might mean you forgot to implement a feature. Make a habit of fixing warnings as soon as you see them.
Mixing up warnings and errors
Sometimes beginners see any red text in the terminal and panic, or see yellow text and think everything is broken. Remember: warnings are advisory, errors are fatal. Check whether the message says warning: or error:. If it says warning:, your program will still build and run.
Not reading the whole error message
Rust error messages are long, but they are packed with useful information. The help: lines often contain the exact code you need to add or change. Read the whole message before searching online.
Randomly changing code until the error disappears
This might work sometimes, but it can introduce new bugs. Instead, understand why the error happened. The error message explains the type mismatch, missing trait, or syntax problem. Once you understand the cause, the fix is usually obvious.
Not using cargo check
Running cargo run every time you make a change is slow. Use cargo check for fast feedback, then run cargo run only when you are ready to test the server.
Step-by-Step Routine for Clean Compilation
Here is a simple workflow you can follow every time you write or modify code in your Axum project.
Step 1: Run cargo check
After making any change to your source files, open a terminal in your project directory and run:
cargo check
This quickly compiles your code and reports any warnings or errors.
Step 2: Fix errors first
If cargo check reports errors, fix them before worrying about warnings. Errors prevent your program from building, so nothing else matters until they are gone.
Read each error message carefully, especially the help: lines, and apply the suggested fixes one by one.
Step 3: Address warnings
After all errors are fixed, look at the warnings. For each warning, ask: "Did I mean to use this?" If yes, fix the code to actually use it. If no, remove or suppress the unused code appropriately.
If a warning points to a real bug, fixing it will make your program more correct.
Step 4: Run cargo check again
Once you have made changes, run cargo check again to confirm that both errors and warnings are gone. You should see output like:
Finished dev [unoptimized + debuginfo] target(s) in 0.42s
No warnings or errors means your code is clean.
Step 5: Run cargo run when ready to test
Only after cargo check reports a clean build should you run cargo run to start your Axum server and test it in a browser or with curl.
Following this routine keeps your project in a healthy state. You will catch problems early, avoid accumulating dozens of warnings, and always know whether your code is truly ready to run.
Summary
Warnings and errors are your compiler's way of talking to you. Errors tell you that your code cannot be compiled; warnings tell you that something looks suspicious but is not fatal. Learning to read both kinds of messages quickly is a skill that will save you hours of debugging.
The single most important habit is to run cargo check after every change, fix errors first, and then clean up warnings. Over time, you will start to recognize common messages instantly - unused variables, missing imports, non-async handlers - and your Axum projects will compile smoothly.
Use this decision rule whenever a message appears: if it starts with error:, nothing runs until you fix it, so read the help: line first and change the code it points at. If it starts with warning:, the program still builds, so ask whether the flagged code is something you meant to use - if yes, use it; if no, delete it or mark it intentionally unused. If the message names a lint you do not understand, search for its error code, like E0277, rather than guessing at a fix.