Return Future value from a function

帅比萌擦擦* 提交于 2021-02-05 10:25:10

问题


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)
}

回答1:


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



来源:https://stackoverflow.com/questions/60696505/return-future-value-from-a-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!