gpt4 book ai didi

rust - Rust Rocket 如何推断包含在结果/选项中的返回类型?

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

这可能不是一个高质量的问题,因为我是 Rust 的新手。

我正在使用 Rocket .火箭处理程序可以返回“实现 Responder 特征的任何类型的值”。但是,我注意到我可以将实现 Responder 的东西包装在任意数量的 ResultOption 中,并且一切正常。例如:

#[post("/add_data")]
fn add_data() -> std::result::Result<Option<Response<'static>>, Status> {
Ok(Some(Response::new()))
}

当然,Rocket 中没有代码来处理所有这些不同的返回变体组合,但根据我目前对 Rust 的了解,我没想到这会“正常工作”。有人可以解释发生了什么或它是如何工作的吗?

最佳答案

查看 Responder 的文档的 Provided Implementations .相关的是

Option<T>

If the Option is Some, the wrapped responder is used to respond to the client. Otherwise, an Err with status 404 Not Found is returned and a warning is printed to the console.

Result<T, E> where E: Debug

If the Result is Ok, the wrapped responder is used to respond to the client. Otherwise, an Err with status 500 Internal Server Error is returned and the error is printed to the console using the Debug implementation.

Result<T, E> where E: Debug + Responder

If the Result is Ok, the wrapped Ok responder is used to respond to the client. If the Result is Err, the wrapped Err responder is used to respond to the client.

虽然它不精确,但您可以在下面看到更完整的签名:

impl<'r, R: Responder<'r>> Responder<'r> for Option<R>

impl<'r, R: Responder<'r>, E: Debug> Responder<'r> for Result<R, E>

impl<'r, R: Responder<'r>, E: Responder<'r> + Debug> Responder<'r> for Result<R, E>

所以

  1. Response<'static>工具 Responder<'static> .因此

  2. Option<Response<'static>>工具 Responder<'static> .因此

  3. Result<Option<Response<'static>>, Status>工具 Responder<'static> .

关于rust - Rust Rocket 如何推断包含在结果/选项中的返回类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65498202/

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