GlobalVar is a Rust library that provides two different implementations for managing global variables. This library allows you to safely manage global state in Rust programs, supporting global variables of any type.
- Supports two global variable management approaches:
- Key-value based global variable management
- Pointer-based global variable management
- Supports global variables of any type
- Thread-safe implementation
- Provides both mutable and immutable reference access
- Memory-safe resource management
This approach uses string keys to identify global variables:
use globalvar::global_kv::{init_global_var, fetch_global_var, fetch_global_var_mut, drop_global_var};
// Initialize a global variable
init_global_var("counter", 42_u64);
// Get an immutable reference
if let Ok(value) = fetch_global_var::<u64>("counter") {
println!("Counter value: {}", value);
}
// Get a mutable reference and modify
if let Ok(value) = fetch_global_var_mut::<u64>("counter") {
*value += 1;
}
// Remove the global variable
drop_global_var::<u64>("counter");This approach directly manages global pointers:
use globalvar::global_ptr::{def_global_ptr, get_global, get_global_mut, undef_global_ptr};
// Create a global variable and get its pointer
let ptr = def_global_ptr(42_u64);
// Get an immutable reference
let value = get_global::<u64>(ptr);
println!("Value: {}", value);
// Get a mutable reference and modify
let value = get_global_mut::<u64>(ptr);
*value += 1;
// Remove the global variable
undef_global_ptr::<u64>(ptr);This library uses unsafe Rust code to implement global state management but provides a safe public API. When using it, please note:
- Ensure correct type matching between storage and retrieval
- Clean up global variables when they are no longer needed
- Be mindful of synchronized access in multi-threaded environments
- Uses
Mutexto ensure thread safety - Uses
HashMapto store key-value pairs - Supports dynamic addition and removal of global variables
- Provides error handling mechanisms
- Directly manages memory pointers
- Lighter-weight implementation
- Suitable for fixed global states
- Requires more careful memory management
- This library is primarily intended for scenarios requiring global state management
- Consider other state management solutions first, and only use global variables when truly necessary
- The key-value based implementation offers better safety and convenience
- The pointer-based implementation offers better performance but requires more careful handling
[To be added]
Issues and Pull Requests are welcome!