Trait AsyncTryFrom

Source
pub trait AsyncTryFrom<T>: Sized {
    type Error: Debug;

    // Required method
    fn async_try_from<'async_trait>(
        value: T,
    ) -> Pin<Box<dyn Future<Output = Result<Self, Self::Error>> + Send + 'async_trait>>
       where Self: 'async_trait;
}
Expand description

Trait for asynchronous fallible conversions from a type T.

This trait allows for conversions that may fail, returning a Result wrapped in a Future.

§Example

use async_from::{ async_trait, AsyncTryFrom };
use std::num::ParseIntError;

struct MyNumber( u32 );

#[ async_trait ]
impl AsyncTryFrom< String > for MyNumber
{
  type Error = ParseIntError;

  async fn async_try_from( value : String ) -> Result< Self, Self::Error >
  {
    let num = value.parse::< u32 >()?;
    Ok( MyNumber( num ) )
  }
}

#[ tokio::main ]
async fn main()
{
  match MyNumber::async_try_from( "42".to_string() ).await
  {
    Ok( my_num ) => println!( "Converted successfully: {}", my_num.0 ),
    Err( e ) => println!( "Conversion failed: {:?}", e ),
  }
}

Required Associated Types§

Source

type Error: Debug

The error type returned if the conversion fails.

Required Methods§

Source

fn async_try_from<'async_trait>( value: T, ) -> Pin<Box<dyn Future<Output = Result<Self, Self::Error>> + Send + 'async_trait>>
where Self: 'async_trait,

Asynchronously attempts to convert a value of type T into Self.

§Arguments
  • value - The value to be converted.
§Returns
  • Result<Self, Self::Error> - On success, returns the converted value. On failure, returns 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.

Implementors§