Skip to content
expected item, found ...

expected item, found ...

DodaTech 3 min read

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 fn keyword 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 use statements 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

Does this error occur in Rust scripts or REPLs too?
Rust does not have an official REPL or scripting mode. Every Rust program must have a fn main() entry point. Third-party tools like evcxr provide REPL-like experiences but are not part of the standard toolchain.
Can I have multiple functions in the same file?
Yes. A single .rs file can contain many items: functions, structs, enums, constants, and use statements. Only executable statements must be inside function bodies.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro