0

For some context, I have worked with Java, Node. My experience is mostly web-backend. Something we usually use in those kind of projects is a single db connection and inject/refer to the connection and build abstractions from that.

I'm looking to do the same thing, although not a web server. I tried searching for singleton in rust but there are multiple solutions. some are with libraries and some with unsafe etc...How can this be achieved in Rust or am I trying to force rust into something it's not. I really don't want/like everything to be passed on through function calls. Makes it harder to refactor if needed.

  • 1
    Does this answer your question? [Rust warp+sqlx service : idiomatic way of passing DBPool from main to handlers](https://stackoverflow.com/questions/71202762/rust-warpsqlx-service-idiomatic-way-of-passing-dbpool-from-main-to-handlers) - Also, please avoid unsafe as much as you can. Only when doing ffi, or when safe code makes one's application significantly slower, should one reach for unsafe. – Caesar Mar 12 '22 at 13:16
  • 1
    Are you really refering to a single connection? The usual approach is a pool. You can use something like `lazy_static` for global sharing, or share it in thread local storage – peterulb Mar 12 '22 at 18:09
  • 1
    Singletons are usually an anti-pattern. It's generally better to give each function/object only the dependencies it needs to perform its task instead of relying on global state. – cdhowie Mar 12 '22 at 20:17

0 Answers0