Based on Rust's conventions, common practices in the ecosystem (including the standard library and popular crates), and guidelines from sources like the Rust Book, Rust API Guidelines, and rustfmt, I'll explain the recommended placement of mod statements relative to use statements. I'll also provide examples and reasoning.
Recommended Order: Put mod Statements Before use Statements
In a typical Rust source file (e.g., lib.rs, main.rs, or a module file like foo.rs), the high-level structure should look like this:
File-level comments or license header (optional, but common).
Outer attributes (e.g., #[allow(unused_imports)] or #[cfg(test)]).
Inner attributes (e.g., #![no_std] or #![feature(some_feature)]).
mod declarations (for submodules).
use statements (imports, grouped and sorted alphabetically by rustfmt).
Constants, statics, or other top-level declarations (e.g., const FOO: u32 = 42;).
The rest of your code (structs, enums, traits, impl blocks, functions, etc.).
Tests (usually at the bottom, inside a #[cfg(test)] mod tests { ... } block).
This order isn't strictly enforced by the compiler or rustfmt (which focuses more on formatting within sections), but it's a strong convention for readability, maintainability, and logical flow. Here's why:
Key Reasons for This Order
Logical Dependency: mod statements declare modules (e.g., mod foo;), which makes them available in the crate's module tree. If you want to import something from that module (e.g., use crate::foo::Bar;), the module must be declared before the use statement. If you reverse the order, the compiler will error out with something like "cannot find module foo".
Example (this compiles):
rust
mod foo; // Declare the module first (assumes foo.rs exists)
use crate::foo::Bar; // Now you can import from it
Example (this does NOT compile):
rust
use crate::foo::Bar; // Error: foo isn't declared yet!
mod foo;
Readability and Convention:
Declaring modules first gives readers an immediate overview of the file's structure (e.g., "this file has submodules X, Y, and Z").
use statements often depend on those modules (or external crates), so it makes sense to list them afterward.
This mirrors how Rust's own standard library and tools like Cargo organize code. For example, check out lib.rs in crates like serde or Rust's std::collections—mod often comes early.
The Rust Book (Chapter 7 on modules) shows examples with mod at the top of files like lib.rs.
rustfmt Compatibility: rustfmt will automatically group and sort your use statements (e.g., alphabetically, merging where possible). It doesn't reorder mod vs. use, but following the convention avoids manual tweaks. Run cargo fmt to standardize.
Edge Cases:
If your file has no mod statements (e.g., a simple utility module), just start with use.
If your use statements don't depend on local modules (e.g., only importing from std or external crates), the order is flexible—but stick to the convention for consistency.
In main.rs or lib.rs, mod is especially common at the top to define the crate's module hierarchy.
Example: A Typical lib.rs File
rust
// SPDX-License-Identifier: MIT
// (Optional license header or doc comment)
#![allow(dead_code)] // Inner attribute
// Declare submodules first
pub mod config;
mod utils; // Can be private if needed
pub mod api {
// Inline module (less common, but if used, it goes here too)
pub fn hello() { println!("Hello"); }
}
// Now imports (grouped and sorted by rustfmt)
use std::collections::HashMap;
use crate::config::Config; // Depends on the mod config; above
use crate::utils::helper_fn;
// Constants or globals
const VERSION: &str = "1.0.0";
// Your code
pub struct MyStruct {
data: HashMap<String, String>,
}
impl MyStruct {
pub fn new(config: Config) -> Self {
let mut data = HashMap::new();
data.insert("key".to_string(), helper_fn());
Self { data }
}
}
// Tests at the bottom
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
let config = Config::default();
let s = MyStruct::new(config);
assert!(!s.data.is_empty());
}
}
When Might You Deviate?
Inline Modules: If you're defining a module inline (e.g., pub mod foo { ... }), it can go anywhere in the file as long as dependencies are satisfied. But for consistency, still put it before use if possible.
Large Files: In very large files, some people group related mod and use together, but this is rare and can reduce readability—split into smaller modules instead.
Personal Projects: If it's a small script or prototype, order matters less. But for shared code, follow conventions to make it easier for others (and tools like rust-analyzer).
Tools and Resources to Help
rustfmt: Run cargo fmt to auto-format. Configure it in rustfmt.toml if you need custom import grouping (e.g., imports_granularity = "Crate").
clippy: Run cargo clippy for lints on unused imports or style issues.
Rust API Guidelines: See the "C-STABLE" section for stability and organization tips.
Rust Book: Chapter 7 has examples of module organization.
Community Examples: Look at popular crates on crates.io (e.g., tokio, reqwest) or Rust's source on GitHub.
If your project has a specific style guide (e.g., in a large team), follow that. Otherwise, sticking to mod before use will keep your code clean, conventional, and error-free. If you share a code snippet or error message, I can give more tailored advice!
User
Rust code style: should I put the mod statements at the top of the file, or after the use statements ?
Assistant
Based on Rust's conventions, common practices in the ecosystem (including the standard library and popular crates), and guidelines from sources like the Rust Book, Rust API Guidelines, and rustfmt, I'll explain the recommended placement of mod statements relative to use statements. (I'm assuming "mode statements" is a typo for "mod statements"—if you meant something else like "mode" in a different context, feel free to clarify!)
Recommended Order: Put mod Statements Beforeuse Statements
In a typical Rust source file (e.g., lib.rs, main.rs, or a module file like foo.rs), the high-level structure should look like this:
use statements (imports, grouped and sorted alphabetically by rustfmt).
Constants, statics, or other top-level declarations.
The rest of your code (structs, enums, traits, impl blocks, functions, etc.).
Tests (usually at the bottom, inside a #[cfg(test)] mod tests { ... } block).
This isn't strictly enforced by the compiler, but it's a strong convention for readability, maintainability, and logical flow. Here's why, along with examples.
Key Reasons for This Order
Logical Dependency and Compiler Requirements: mod statements declare modules (e.g., mod foo;), making them part of the crate's module tree. If you need to import from that module (e.g., use crate::foo::Bar;), the mod must come before the use—otherwise, the compiler will error out (e.g., "cannot find module foo").
Valid Example (compiles):
rust
mod foo; // Declare the module first (assumes foo.rs exists)
use crate::foo::Bar; // Now you can import from it
use crate::foo::Bar; // Error: foo isn't declared yet!
mod foo;
Readability and Convention:
Declaring modules first provides an immediate overview of the file's structure (e.g., "this file includes submodules X and Y").
use statements often depend on those modules or external crates, so listing them afterward creates a logical flow.
This matches how Rust's standard library, Cargo-generated projects, and popular crates (e.g., serde, tokio) organize code. The Rust Book (Chapter 7) shows mod at the top in examples.
rustfmt auto-formats use statements (grouping and sorting them), but it doesn't reorder sections—following this order keeps things consistent.
Edge Cases:
If your file has no mod statements, just start with use.
If use statements don't depend on local modules (e.g., only use std::collections::HashMap;), the order is flexible—but stick to the convention for consistency.
Inline modules (e.g., pub mod foo { ... }) can go anywhere dependencies allow, but prefer placing them before use.
Example: A Typical lib.rs File
rust
// Optional doc comment or license
#![allow(dead_code)] // Inner attribute
// Submodules first
pub mod config;
mod utils;
// Imports next (rustfmt will sort/group these)
use std::collections::HashMap;
use crate::config::Config; // Depends on mod config; above
use crate::utils::helper_fn;
// Constants
const VERSION: &str = "1.0.0";
// Code
pub struct MyStruct {
data: HashMap<String, String>,
}
impl MyStruct {
pub fn new(config: Config) -> Self {
let mut data = HashMap::new();
data.insert("key".to_string(), helper_fn());
Self { data }
}
}
// Tests at the bottom
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
let config = Config::default();
let s = MyStruct::new(config);
assert!(!s.data.is_empty());
}
}
Tools to Help Enforce Style
rustfmt: Run cargo fmt to auto-format imports and more. Customize in rustfmt.toml (e.g., for import grouping).
clippy: Run cargo clippy for lints on unused imports or style.
Resources: Rust Book (Chapter 7), Rust API Guidelines, or examples from crates like reqwest on GitHub.
If your project has a team style guide, follow that. Otherwise, mod before use is the way to go—it's conventional, prevents errors, and improves code flow. If you share a specific code snippet or error, I can provide more targeted advice!