pub trait Service<Request> {
type Response;
type Error;
// Required method
fn call(
&self,
req: Request,
) -> impl Future<Output = Result<Self::Response, Self::Error>>;
}
Expand description
This Service
trait leverages impl Trait
to offer a efficient and flexible
approach to building asynchronous services in Rust. It addresses key challenges
faced with Tower’s Service
trait:
- Efficient Borrowing: Futures can capture
&self
or&mut self
, eliminating unnecessary cloning. - Simplified Implementation: Removes the need for manual state management and
Box<Pin<...>>
, allowing for more idiomatic async Rust code.
§Key Features
- Functions as a request handler rather than a future factory.
- Eliminates the need for a
poll_ready
function. - Allows for more inline code optimization using
impl Trait
. - Supports both shared immutable (
&self
) and exclusive mutable (&mut self
) access.
§Resource Efficiency
This design maintains reference relationships, incurring costs only when mutability is required, unlike Tower’s shared ownership model where each share has an associated cost.
Required Associated Types§
Required Methods§
Sourcefn call(
&self,
req: Request,
) -> impl Future<Output = Result<Self::Response, Self::Error>>
fn call( &self, req: Request, ) -> impl Future<Output = Result<Self::Response, Self::Error>>
Asynchronously process the request and return the response.
This method takes a shared reference to self
, allowing for efficient
use of a single Service
instance across multiple calls. For mutable state,
consider using synchronization primitives like Mutex
or RefCell
.
§Arguments
req
- The request to be processed by the service.
§Returns
A Future
that resolves to a Result
containing either the service’s
response or an error.
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.