basic_usage/
basic_usage.rs

1mod basic_usage_example {
2    use async_trait::async_trait;
3    use async_try_from::{AsyncTryFrom, ValidateIntegrity, AsyncCreateWithAndValidate};
4    use std::io;
5
6    // A simple struct that we will create asynchronously
7    pub struct MyType;
8
9    // Implement async creation from a String
10    #[async_trait]
11    impl AsyncTryFrom<String> for MyType {
12        type Error = io::Error;
13
14        async fn new(input: &String) -> Result<Self, Self::Error> {
15            if input.is_empty() {
16                Err(io::Error::new(io::ErrorKind::Other, "Input string is empty."))
17            } else {
18                Ok(MyType)
19            }
20        }
21    }
22
23    // Implement a basic validation check
24    #[async_trait]
25    impl ValidateIntegrity for MyType {
26        type Error = io::Error;
27
28        async fn validate_integrity(&self) -> Result<(), Self::Error> {
29            // Add real integrity checks here if needed
30            Ok(())
31        }
32    }
33
34    // Demonstrate creating and validating our type in one step
35    pub async fn run_example() -> Result<(), Box<dyn std::error::Error>> {
36        let input = "Some input".to_string();
37        let _instance = MyType::new_and_validate(&input).await?;
38        println!("Successfully created and validated MyType instance.");
39        Ok(())
40    }
41}
42
43#[tokio::main]
44pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
45    // In a real project, you could call:
46    // This example keeps main synchronous for demonstration.
47    println!("Run 'cargo run --example basic_usage' to see the async creation and validation in action.");
48    Ok(basic_usage_example::run_example().await?)
49}