gpt4 book ai didi

rust - 无论如何混合::结果与 std::io::Result

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

谁能帮我理解为什么这段代码编译得很好:

use actix_web::{App, HttpServer};
use anyhow::Result;

mod error;

#[actix_rt::main]
async fn main() -> Result<()> {
HttpServer::new(|| App::new())
.bind("127.0.0.1:8080")?
.run()
.await?;

Ok(())
}

虽然这不编译:
use actix_web::{App, HttpServer};
use anyhow::Result;

mod error;

#[actix_rt::main]
async fn main() -> Result<()> {
HttpServer::new(|| App::new())
.bind("127.0.0.1:8080")?
.run()
.await
}


有错误:
error[E0308]: mismatched types
--> src/main.rs:6:1
|
6 | #[actix_rt::main]
| ^^^^^^^^^^^^^^^^^ expected struct `anyhow::Error`, found struct `std::io::Error`
7 | async fn main() -> Result<()> {
| ---------- expected `std::result::Result<(), anyhow::Error>` because of return type
|
= note: expected enum `std::result::Result<_, anyhow::Error>`
found enum `std::result::Result<_, std::io::Error>`
= note: this error originates in an attribute macro (in Nightly builds, run with -Z macro-backtrace for more info)

这两个例子有什么根本区别?

最佳答案

问题是第二个例子返回 Result<(), std::io::Error>这是通过启动服务器返回的,而第二个返回的是 Result<(), anyhow::Error>Ok(()) 的形式.

第一个例子起作用的原因是 ?运算符(或 try! 宏)执行从返回的任何错误到函数返回类型的错误的转换。

来自 the docs :

In case of the Err variant, it retrieves the inner error. try! then performs conversion using From. This provides automatic conversion between specialized errors and more general ones.

关于rust - 无论如何混合::结果与 std::io::Result,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62241198/

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