问题
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