I'm researching and playing with Rust's async/.await
to write a service in Rust that will pull from some websockets and do something with that data. A colleague of mine (who did this similar "data feed importing" in C#) has told me to handle these feeds asynchronously, since threads would be bad performance-wise.
It's my understanding that, to do any async in Rust, you need a runtime (e.g. Tokio). After inspecting most code I've found on the subject it seems that a prerequisite is to have a:
#[tokio::main]
async fn main() {
// ...
}
which provides the necessary runtime which manages our async
code. I came to this conclusion because you cannot use .await
in scopes which are not async
functions or blocks.
This leads me to my main question: if intending to use async
in Rust, do you always needs an async fn main()
as described above? If so, how do you structure your synchronous code? Can structs have async
methods and functions implemented (or should they even)?
All of this stems from my initial approach to writing this service, because the way I envisioned it is to have some sort of struct which would handle multiple websocket feeds and if they need to be done asynchronously, then by this logic, that struct would have to have async
logic in it.