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?
Constants are declared using the const keyword while variables are declared using the let keyword.
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.
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.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With