rust - 从函数返回 future 值

标签 rust rust-tokio

我最近开始学习Rust,但不确定如何从应该返回Result的函数中返回将来的值。当我尝试仅返回响应变量并删除Result输出时,出现错误:无法在返回? 的函数中使用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()的期望是获取并打印响应值:
fn main() {
    let response = download();
    println!("{:?}", response)
}

最佳答案

我想你的代码应该看起来像这样

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 playground link

关于rust - 从函数返回 future 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61983340/

相关文章:

rust - 如何在Rust中为终端设置动画

rust - GMP - mpf_cmp_si 对于负值无法正常工作

rust - @ operator bindings over extra conditionals with match guards的好处

rust - tokio::run() 和发送标记的编译错误

asynchronous - tokio async rust 上的 Yield 是什么意思?

rust - zipper 两条链后如何反转

rust - 你如何在 Rust 中使用父模块导入?

rust - 即使我有#[tokio::main],为什么仍然出现错误 “there is no reactor running, must be called from the context of Tokio runtime”?

Rust Tokio - 监控停滞的任务

rust - 某些 tokio 功能的导入未解决