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(
    remote_path: String,
    fs_id: u64,
    app_id: u32,
    func: DF,
) -> Result
where
    DF: Fn(String, u64, u32) -> Result,
{
    func(remote_path, fs_id, app_id)
}

fn get_download_link(remote_path: String, fs_id: u64, app_id: u32) -> Result {
    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(
    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 {
    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());
}


你可能感兴趣的:(rust Fn 和 async - 2021-03-02)