Global variable across modules


#1

Is it possible to declare a global variable and use it across several files/modules in rust, like i can do for example in c/c++ with the “extern” keyword?


#2

statics have exactly the same privacy rules as other items: you can write pub static FOO: Type = value; and it will be accessible externally. Whether having a publicly accessible global is a great idea or not is a different question: Rust certainly imposes more restrictions than C or C++ to ensure safety (it is easy to get unsafe multithreaded code with globals, and even single threaded code can be problematic). Designs more suited to Rust include using context objects instead of globals, or having a private global with accessor/manipulator functions.