rust Fn 和 async - 2021-03-02

Fn 使用普通函数作为实际调用参数

use std::future::Future;

#[tokio::main]
async fn main() {
    println!("Hello, world!");
    let _ = call_get_url("12345".to_string(), 123456, 1234567890, &get_download_link);
    println!("Hello, world2!");
}

fn call_get_url<DF>(
    remote_path: String,
    fs_id: u64,
    app_id: u32,
    func: DF,
) -> Result<String, String>
where
    DF: Fn(String, u64, u32) -> Result<String, String>,
{
    func(remote_path, fs_id, app_id)
}

fn get_download_link(remote_path: String, fs_id: u64, app_id: u32) -> Result<String, String> {
    println!(
        "get_download_link:remote_path:{},fs_id:{},:app_id{}",
        remote_path, fs_id, app_id
    );
    return Ok("this is the download link ".to_string());
}

Fn 使用异步函数作为实际调用参数

use std::future::Future;

#[tokio::main]
async fn main() {
    println!("Hello, world!");
   
    let _ = call_get_url_async(
        "12345".to_string(),
        123456,
        1234567890,
        &get_download_link_async,
    )
    .await;
    println!("Hello, world2!");
}

async fn call_get_url_async<T>(
    remote_path: String,
    fs_id: u64,
    app_id: u32,
    func: impl Fn(String, u64, u32) -> T,
) -> T::Output
where
    T: Future,
{
    return func(remote_path, fs_id, app_id).await;
}

async fn get_download_link_async(
    remote_path: String,
    fs_id: u64,
    app_id: u32,
) -> Result<String, String> {
    println!(
        "get_download_link_async:remote_path:{},fs_id:{},:app_id{}",
        remote_path, fs_id, app_id
    );
    return Ok("this is the download link async ".to_string());
}


©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容