How to use Global structure with single variable in all the files without using Unsafe

Hi, i am new to Rust programming.In c programming, i have a Global structure and its variable that can be used in entire project.So,if i modify in single file it has to effect in that particular structure.How can i do this in Rust programming.

I want to have only one structure variable that to be shared in all files ,how it's possible???

Thanks in advance

Mutable global variables are very strongly discouraged in Rust, and you should probably find a different way to structure your code.


Thanks for ur reply..if i use unsafe ,then i am able to access Global structure variable.

Global mutable variables are unsafe, because they can be accessed by any thread (single-threaded programs don't exist from Rust's perspective).

You can make them safe by putting the value in a Mutex. You may need lazy_static to initialize it.

Alternatively, consider passing the value as an argument to all functions that need it. You'll need either Mutex or RefCell to share it via &, or additionally wrap it in Rc/Arc if the borrow checker complains.

If the fields are just integers, you can also use atomics.

So it would appear. However, if you violate any of the guarantees that you are required to make to the compiler about your unsafe code, you have UB (undefined behavior), which by definition permits the compiler to optimize your code into not working correctly.

unsafe is a way for you to assume some of the responsibility for meeting the compiler's requirements; it is not a way to bypass those obligations. In particular, even the possibility of concurrent mutable access (whether your logic actually causes that, or not) is sufficient to cause massive miscompilation.

It's also worth mentioning that, even though mutable globals are more common in C, most of those same obligations exist in C as well, so naive global-mutating code is just as likely to invoke UB and not actually work in both languages (even if it happens to appear to work today).

For your own sanity, please use whatever combination of Arc/Mutex/RefCell/lazy_static/just passing the thing around will make your code work without that unsafe. A static mut variable simply is not worth the risk unless you're dealing with special memory in bare metal code, or you have done the safe implementation already and written a thorough test and benchmark suite to prove it's not fast enough.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.