gpt4 book ai didi

rust - 从函数返回 future 值

转载 作者:行者123 更新时间:2023-12-03 11:48:40 25 4
gpt4 key购买 nike

我最近开始学习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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com