gpt4 book ai didi

rust - std::result::Result 无法使用默认格式化程序格式化

转载 作者:行者123 更新时间:2023-12-03 11:42:50 24 4
gpt4 key购买 nike

我是rust的新手,正在尝试获取请求响应主体,我当前的代码是:

let client = reqwest::Client::new();
let response_text = client.get("google").send();
println!("{}", response_text);
但这会产生错误
std::result::Result<reqwest::Response, reqwest::Error>` cannot be formatted with the default formatter

最佳答案

精简版
使用"{:?}"而不是"{}"调试输出。
长版
我必须修改您的代码以获取相同的错误消息:

pub fn dummy() {
let client = reqwest::blocking::Client::new();
let response_text = client.get("google").send();
println!("{}", response_text);
}
它使用阻止API而不是异步API。异步API给出了类似但略为复杂的错误。
完整的错误消息是:
error[E0277]: `std::result::Result<reqwest::blocking::Response, reqwest::Error>` doesn't implement `std::fmt::Display`
--> src/lib.rs:5:20
|
5 | println!("{}", response_text);
| ^^^^^^^^^^^^^ `std::result::Result<reqwest::blocking::Response, reqwest::Error>` cannot be formatted with the default formatter
|
= help: the trait `std::fmt::Display` is not implemented for `std::result::Result<reqwest::blocking::Response, reqwest::Error>`
= note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
= note: required by `std::fmt::Display::fmt`
= note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)
第一行给出了 std::result::Result<reqwest::blocking::Response, reqwest::Error>没有实现 std::fmt::Display的根本原因。
问题是使用“{}”进行格式化需要一个对象支持 std::fmt::Display,而Result对象不支持该格式。 (您可以通过查看它在 https://doc.rust-lang.org/std/result/enum.Result.html上实现的特征列表来进行检查)
只要 Result的两个参数都可以,就可以实现 std::fmt::Debug
就像这里的情况一样。
这是必须使用 "{:?}"而不是 {}进行格式化的特征。
如果您不想调试输出,则需要更加努力地获取内容。您会想要类似
   match response_text {
Err(e) => eprintln!("Error: {:?}", e);
Ok(v) => println!("Body: {}", v.text().unwrap();
}
但是即使使用非UTF8输入也无法正确处理这种情况,并且展开会出现 panic 。

关于rust - std::result::Result <reqwest::Response,reqwest::Error>无法使用默认格式化程序格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63838828/

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