首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在`Result<reqwest::blocking::Response,reqwest::Error>`中找不到锈蚀- json方法

在`Result<reqwest::blocking::Response,reqwest::Error>`中找不到锈蚀- json方法
EN

Stack Overflow用户
提问于 2022-02-17 21:57:27
回答 1查看 622关注 0票数 -1

我想使用reqwest,但我不能--我有一个错误:

代码语言:javascript
复制
let users: Vec<User> = response.json();
                                ^^^^ method not found in `Result<reqwest::blocking::Response, reqwest::Error>

这是我的密码:

代码语言:javascript
复制
use reqwest::Error;
use tokio;

#[derive(Deserialize, Debug)]
struct User {
    origin: String
}


#[tokio::main]
pub fn main() {

    let request_url = format!("https://api.ipify.org");
    println!("{}", request_url);
    let response = reqwest::blocking::get(&request_url);

    let users: Vec<User> = response.json();
    println!("{:?}", users);
}

我的依赖关系:

代码语言:javascript
复制
[dependencies]
serde = { version = "1.0.136", features = ["derive"]}
reqwest = { version = "0.11.9", features = ["blocking", "json"]}
tokio = { version = "1.17.0", features = ["full"] }

为什么会发生这种事?我该怎么做才能解决这个问题?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-02-18 00:20:35

reqwest::blocking::get()返回一个reqwest::Result<Response>,它是内置Result类型的别名。Result表示一个可能失败的操作,因此您不一定有响应--您可能会有一个错误。

您需要使用?运算符将错误从函数中传播出去,也可以使用matchif let来展开值。

例如,使用match

代码语言:javascript
复制
let response = match reqwest::blocking::get(&request_url) {
    // Unwraps the response value from the Result
    Ok(r) => r,

    // Unwraps the error from the Result and terminates main()
    Err(err) => {
        println!("Request failed: {}", err.to_string());
        return;
    },
};

进一步读:

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71165876

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档