Search code examples
rustrust-tokio

Return Future value from a function


I recently started to learn Rust and I'm not sure how I can return future value from a function that should return a Result. When I try to return just the response variable and remove the Result output, I get an error: cannot use the ? operator in a function that returns std::string::String

#[tokio::main]
async fn download() -> Result<(),reqwest::Error> {
    let url = "https://query1.finance.yahoo.com/v8/finance/chart/TSLA";
    let response = reqwest::get(url)
                            .await?
                            .text()
                            .await?;
    Ok(response)
 }

What I expect in main() is to get and print the response value:

fn main() {
    let response = download();
    println!("{:?}", response)
}

Solution

  • I suppose your code should looks something like this

    extern crate tokio; // 0.2.13
    
    async fn download() -> Result<String, reqwest::Error> {
        let url = "https://query1.finance.yahoo.com/v8/finance/chart/TSLA";
    
        reqwest::get(url).await?.text().await
    }
    
    #[tokio::main]
    async fn main() {
        let response = download().await;
    
        println!("{:?}", response)
    }
    

    Here is rust playground link