I'm looking for a way to manage constant strings in a Rust project. The hope is to manage my strings from a single file and avoid having the same string literals all over the place in the project.

Would the "Rust" way of doing this be to create something like constants.rs which would include my strings, something like...

pub const COMMONSTRING: &str = "common string value";
pub const ANOTHERCOMMONSTRING: &str = "another common string value";

...and then use mod constants; in the subsequent locations where they are needed? The idea is that I will be using these constant strings later in format!() calls with various other string literals. This is the approach I have been taking so far and it seems to be working, i.e.

mod constants;
let path_str = &format!("./{}", constants::PATHSTRING);

Being new to Rust I wanted to make sure this seemed like a logical way to handle this, any feedback would be much appreciated!

  • 1
    cross post Oct 22, 2019 at 18:09
  • 1
    Per Code Review, I was instructed to post here. "Welcome back to CodeReview. Unfortunately, asking for best practices question is out of scope on this site, see help center. Software Engineering can be the appropriate place for this question, but you're expected to define how you'll measure the "best" way, see softwareengineering.stackexchange.com/help/on-topic." The Code Review question has been deleted and this question has been modified.
    – temarsden
    Oct 22, 2019 at 18:11

1 Answer 1


I don't know if there is a specific "Rust" way of doing this, but I would definitely use const variables as well. Coming from C++, I already do the same thing there (using constexpr). This compiles down to code that is the same as if you would just manually write the same string over and over again. Sometimes I even use this for strings that are only used once, (e.g.) to make the code more readable.

For having a specific constants.rs, it depends imo. If there are a lot of these constant strings and you all literally need them everywhere in your project, then structuring your project by having these in a separate file is great. However, from my experience, you rarely use strings all over a project. It's more likely it is spread over a smaller scope. So for strings that are only used in 1 file, I would define it in that file and for strings that are used over multiple files, I would define it in the smallest shared parent module (mod.rs). This prevents a clutter of strings in a constants.rs, that don't necessarily have something in common.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.