Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 539
user3384741 Avatar asked May 25 '16 07:05

user3384741


People also ask

How do you declare constants in Rust?

Constants are declared using the const keyword while variables are declared using the let keyword.

Does Rust have const?

Rust has two different types of constants which can be declared in any scope including global. Both require explicit type annotation: const : An unchangeable value (the common case). static : A possibly mut able variable with 'static lifetime.

What is const FN?

A const fn is a function that one is permitted to call from a const context. Declaring a function const has no effect on any existing uses, it only restricts the types that arguments and the return type may use, as well as prevent various expressions from being used within it.

What does the MOD keyword do Rust?

Organize code into modules. Like struct s and enum s, a module and its content are private by default, inaccessible to code outside of the module.


1 Answers

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

This should work:

pub fn do_stuff() {
    println!("This is version: {}", crate::VERSION);
}
like image 97
Dogbert Avatar answered Nov 13 '22 11:11

Dogbert