How to store this variable globally instead of passing it all over?


#1

Hello!

I am trying to use this library:

In order to do this properly, I need to initialize the connection as such:
// connect to redis
let client = try!(redis::Client::open(“redis://127.0.0.1/”));
let con = try!(client.get_connection());

Ideally I could have con as a global variable but I can’t start it it as a null, since rust doesn’t support nulls, and I believe I can’t call a function before main executes to set those variables.

Should I just initialize con in main and pad it all over? Is there a better way to do this? Ideally I’d like a standalone library and my calling functions don’t have to deal with this.

Thank you!!


#2

If you really want it to be global, one option is http://crates.io/crates/lazy_static


#3

You can use an Option and initialize it with None.


#4

What about a thread local? https://doc.rust-lang.org/std/thread/struct.LocalKey.html