user3384741
user3384741

Reputation: 1340

Rust constants in different modules?

I have this "main.rs" file which I declare a version constant.

pub const VERSION: &'static str = "v2";
mod game;
fn main() {
   do_stuff();
}

Then I want to access this global constant in a different module "game.rs":

pub fn do_stuff() {
   println!("This is version: {}", VERSION);
}

How do I make the constant available everywhere?

Upvotes: 32

Views: 19291

Answers (2)

Dogbert
Dogbert

Reputation: 222128

As VERSION is declared in main.rs, which is a crate root, you can access it using its absolute path: crate::VERSION1.

This should work:

pub fn do_stuff() {
    println!("This is version: {}", crate::VERSION);
}

1 In Rust 2015, ::VERSION could be used, but starting in Rust 2018, crate is required.

Upvotes: 37

chen Jacky
chen Jacky

Reputation: 567

use crate::VERSION
println!("version: {}", VERSION);

will be better.

Upvotes: 2

Related Questions