How to use a singleton services in actix-web?

Hi!
I try to create a web-service based on actix-web and got trouble. All my handlers should use single trait that make a request to elasticsearch. Http requests are async, so trait should use .await for waiting it results. But .await can be used only in async functions and rust don't allow async functions in traits!
How to solve this situation? Is there some pattern for this case? Or async should be used only for procedural programming?

You can use the async-trait crate to use async functions in traits. It is marginally slower than writing out the code with traits, as every time a method is called a heap allocation has to occur, but that shouldn't be too much of a problem.

I read about it. But it marked like "experimental". Is it other ways exist?

Is it? Where did you read that? async-trait is a stable and widely used crate, I would by no means consider it experimental.

Hm... maybe I got muddled. Thank you!

I suspect what you saw is the native compiler support for async traits which is not something that is functioning in stable rust. The async-trait crate is a workaround for stable rust that imposes the limitation that the returned future by the method must allocate to the heap. The eventual goal is for the compiler to have native support for async trait methods with that limitation removed.

1 Like