expected item, found ...
The “expected item, found …” error in Rust means the compiler found a statement or expression at the file level where only items like functions, structs, enums, constants, or imports are allowed. Rust’s top-level scope only accepts declarations, not executable code.
What It Means
In Rust, a source file is a collection of items. Items include function definitions, type definitions, modules, use declarations, and constant definitions. Statements like let, println!, or arithmetic expressions are not items. Placing them outside a function body triggers this error.
Why It Happens
- You wrote executable code (assignments, function calls) directly in the file, not inside a function.
- You forgot the
fnkeyword when defining a function. - You started a line with an expression thinking it is a declaration.
- You are coming from Python or JavaScript where top-level code runs on import.
- You put
usestatements after executable code instead of at the top.
How to Fix It
1. Wrap code inside the main function
Executable statements must live inside a function body:
// Error: expected item, found `let`
let x = 5;
println!("{}", x);
// Fix: wrap in main()
fn main() {
let x = 5;
println!("{}", x);
}2. Add the fn keyword if defining a function
A common mistake is omitting fn:
// Error: expected item, found `main`
main() {
println!("Hello");
}
// Fix: add fn keyword
fn main() {
println!("Hello");
}3. Move imports to the top and code to functions
Rust requires use statements before any other items:
fn main() {
use std::fs; // valid but unusual
}
// Better: move use to the top level
use std::fs;
fn main() {
// use the import here
}4. Wrap test code in a test function
If you are writing quick experiments, put them in a function:
// Tests and examples belong inside functions
#[test]
fn test_addition() {
assert_eq!(2 + 2, 4);
}5. Understand Rust’s file model
Every .rs file is a module. Modules contain items. If you want code to run when the file is executed, place it in fn main():
// lib.rs or main.rs
fn setup_logging() {
// this is fine — it is a function item
}
// But this would fail:
// println!("logging setup complete");
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro