Skip to content

Instantly share code, notes, and snippets.

@thehappycheese
Last active May 31, 2024 03:08
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! :)

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