Trait Use

Source
pub trait Use {
    // Provided methods
    fn use_with<U, F: FnOnce(Self) -> U>(self, f: F) -> U
       where Self: Sized { ... }
    fn use_with_async<F, Fut, U>(self, f: F) -> impl Future<Output = U> + Send
       where Self: Sized + Send,
             F: FnOnce(Self) -> Fut + Send,
             Fut: Future<Output = U> + Send { ... }
}
Expand description

A trait that facilitates resource management by ensuring proper usage and subsequent dropping.

This trait provides two methods:

  • use_with: Executes a closure synchronously, consuming the resource.
  • use_with_async: Executes an asynchronous closure, consuming the resource.

Implementing this trait allows for safe and efficient resource handling, ensuring that resources are properly utilized and dropped, even in asynchronous contexts.

Provided Methods§

Source

fn use_with<U, F: FnOnce(Self) -> U>(self, f: F) -> U
where Self: Sized,

Executes a closure synchronously, consuming the resource.

This method takes ownership of self and applies the provided closure f to it. After the closure executes, self is dropped.

§Parameters
  • f: A closure that takes ownership of self and returns a value of type T.
§Returns
  • A value of type T, which is the result of the closure f.
§Examples
use use_with::Use;

struct Resource;

impl Resource {
    fn new() -> Self {
        Resource
    }
}

let result = Resource::new().use_with(|res| {
    // Perform operations with `res`, return anything.
    42
});

assert_eq!(result, 42);
Source

fn use_with_async<F, Fut, U>(self, f: F) -> impl Future<Output = U> + Send
where Self: Sized + Send, F: FnOnce(Self) -> Fut + Send, Fut: Future<Output = U> + Send,

Executes an asynchronous closure, consuming the resource.

This method takes ownership of self and applies the provided asynchronous closure f to it. After the asynchronous operation completes, self is dropped.

§Parameters
  • f: An asynchronous closure that takes ownership of self and returns a future.
§Returns
  • A future that resolves to a value of type U, which is the result of the asynchronous operation.
§Examples
use use_with::Use;
use std::future::Future;

struct Resource;

impl Resource {
    fn new() -> Self {
        Resource
    }
}

// Usage example
let future = Resource::new().use_with_async(|res| async {
    // Perform asynchronous operations with `res`, return anything.
    42
});

// Await the result
assert_eq!(future.await, 42);

Implementors§

Source§

impl<T> Use for T