如何使 returns 文本来自响应的功能?

How to make function that returns text from response?

我是 Rust 的新手,在 python 之后尝试学习它,并且在最简单的任务之一中遇到了问题。
为简单起见,我想编写函数以从 http 响应中获取数据(在本例中为文本)。
src/main.rs

use reqwest;


fn main() {
    let text = get_text();
    println!("Got text {text}")
}

fn get_text() -> String {
    let http_client = reqwest::blocking::Client::new();
    let url = "https://google.com";
    let response = http_client.get(url).send()?.text()?;
    response
}

Cargo.toml

[package]
name = "test"
version = "0.1.0"
edition = "2021"
[dependencies]
reqwest = { version = "0.11", features = ["json", "blocking"] }
openssl = { version = "0.10", features = ["vendored"] }

我想将 get_text() 例程设为 return 字符串类型。
根据reqwest docs.text()returnsResult<String>
据我了解,运算符 ? 意味着调用应该 return Ok<String> 或使用 Err(e)

恐慌

代码编译失败:

 let response = http_client.get(url).send()?.text()?;
cannot use the `?` operator in a function that returns `std::string::String`

这里我先不明白:
如果 return 值仅在 return 之后,为什么要编译比较函数 return 与 .send().text()? 的 return 类型?

而且,好吧,我尝试将 return 类型更改为 Result<String, Box<dyn std::error::Error>>,就像在文档和示例中一样
然后编译器抱怨错误 return type:

 |     response
 |     ^^^^^^^^ expected enum `Result`, found struct `std::string::String`

所以第二个问题是:
当编译器比较函数调用中间和调用结束时的 return 类型时我如何实现我的目标

问号运算符通过 return 传递一个中间 Result::Err 值。这意味着该函数必须将 Result 作为其 return 类型。但是在函数的末尾,您尝试 return 一个字符串。 String 不是 Result 变体,但您可以通过将其包装在 Ok 中使其成为一个变体。

或者,如果您不想介意恐慌,则可以使用“?”你可以使用 '.unwrap()' 然后你的 return 类型可以保持 String.

首先,也是最重要的是,阅读 here 关于 ? operator 的第一个问题的答案。

The ? placed after a Result value is defined to work in almost the same way as the match expressions we defined to handle the Result values

关于您的代码,您应该执行如下操作

use reqwest;

// Have changed main method's return type 
// as using ? operator on result returned by get_text() method
fn main() -> Result<(), Box<dyn std::error::Error>> {

    // unwrapped result from get_text() with ?
    let text = get_text()?;

    // changed formatting
    println!("Got text {}", text);

    // as main method response type is changes return unit type in case of success
    Ok(())
}

fn get_text() -> Result<String, Box<dyn std::error::Error>> {
    let http_client = reqwest::blocking::Client::new();
    let url = "https://google.com";

    let response = http_client
        // form a get request with get(url)
        .get(url)
        // send the request and get Response or else return the error
        .send()?
        // get text from response or else return the error
        .text()?;

    // wrapped response in Result
    Ok(response)
}

希望对您有所帮助。