Skip to content

Instantly share code, notes, and snippets.

@thehappycheese
Last active February 13, 2025 01:01
Show Gist options
  • Save thehappycheese/febd3af1409c3001f8f8fa8a892a53a9 to your computer and use it in GitHub Desktop.
Save thehappycheese/febd3af1409c3001f8f8fa8a892a53a9 to your computer and use it in GitHub Desktop.
Rust folder structure / file structure import example

I love ❀️ rust but I hate 😞 how vague the beginner documentation is about splitting up your project into a practical structure. This is how I do it (for a library project anyway):

.
└── project/
    β”œβ”€β”€ src/
    β”‚   β”œβ”€β”€ lib.rs
    β”‚   β”œβ”€β”€ top_level_module.rs
    β”‚   └── util/
    β”‚       β”œβ”€β”€ mod.rs
    β”‚       β”œβ”€β”€ utility_module_1.rs
    β”‚       β”œβ”€β”€ utility_module_2.rs
    β”‚       └── private_module.rs
    β”œβ”€β”€ cargo.toml
    └── readme.md

./src/lib.rs

mod util;
mod top_level_module;

use util::utility_module_1::{Foo, Bar}
use util::utility_module_1::{Spam, Eggs}
use util::Sneaky;

use top_level_module::Stuff

// Do Stuff

./src/top_level_module.rs

// note: no need for `mod` since that appears in lib.rs
use util::utility_module_1::{Foo, Bar}

pub struct Stuff{
  pub ff:Foo,
  pub bb:Bar,
  // ...
}

./src/util/mod.rs

// we can choose to export sub modules as public submodules here
pub mod utility_module_1.rs
pub mod utility_module_2.rs

// we can also re-export the contents of submodules 
// as if they were defined in the `util` module
mod private_module;
pub use private_module::Sneaky;

./src/util/utility_module_1.rs

pub struct Foo(u8);
pub struct Bar(f64);

./src/util/utility_module_2.rs

// submodules can use code from eachother by pathing from the `crate::` root:
use crate::util::utility_module_1::Foo;

// OR
// they can refer to the module above using `super::`
// in this case super:: refers to util
use super::utility_module_1::Foo;

pub struct Spam();
pub struct Eggs{
    pub aa:Foo
};

./src/util/private_module.rs

pub struct Sneaky();
@DiazRock
Copy link

Thanks very much for this help!

@thehappycheese
Copy link
Author

Thanks very much for this help!

My pleasure, glad to have helped! :)

@NicTanghe
Copy link

Hello reading around i can c that eryone is using the modfile method becouse they cant seem to figure out how the recommended way actually works and just go meh lets use the old way.

Does annyone know how to do it the way it is recommended in the docs (wich are verry unclear)

wich this structure instead of with the mod files.

Option 2 β€’ <folder_name>.rs (the preferred way):

src
    utils
        bar.rs
        foo.rs
    utils.rs
    main.rs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment