Hello all,
I'm wondering if someone can help with the following scenario.
I come from a C background, where the design pattern is somewhat flat. For certain things (such as a database connection), I might have this as a global in that it's declared as extern
from a header file, which means whenever that header file is included, I have access to that database handle.
In Rust, I'm thinking about how I might achieve this from a similar scenario. I know I have the "option" (used in the loosest sense) if using something like: pub static DB: DBType = foo;
but this feels incorrect and seems as though Rust is making you choose a different pattern, which I'm all for!
So... let's say I wrapped this DB example in a struct which holds some additional state:
struct DBState {
connection: String,
path: String,
}
If I then implemented some fn
s on it:
impl DBState {
pub fn new (...);
pub fn connection(...);
}
At some point (presumably from fn main()
although not necessarily so), I'm going to have to instantiate a DBState
to setup a connection to the Database. That fine, and I can do that. But, if I have my code separated into different modules -- some of which might require access to the DBState
's connection()
-- how would I ensure that instantiated instance is available to those modules? As I see, it I have a few options:
- Somehow pass an instance of
DBState
to every function which seems counter-intuitive; - Use a
static
variable in a module. - Would using a
trait
help here?
Options 1 and 2 seem incorrect to me. Option 3 might work, but I'm not sure from a design perspective, how that influences the most straight-forward route.
I hope I've been clear -- and sorry if not, but if I can provide additional context, do please let me know.
Thanks in advance for everyone's thoughts!