从函数返回未来值 [英] Return Future value from a function
本文介绍了从函数返回未来值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我最近开始学习 Rust,但我不确定如何从应该返回 Result 的函数中返回未来值.当我尝试仅返回响应变量并删除结果输出时,出现错误:不能在返回 std::string::String 的函数中使用
?
运算符
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)
}
我期望在 main() 中获取并打印响应值:
What I expect in main() is to get and print the response value:
fn main() {
let response = download();
println!("{:?}", response)
}
推荐答案
我想你的代码应该是这样的
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)
}
这里是 rust 链接
这篇关于从函数返回未来值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文