有人能帮我理解为什么这段代码编译得很好吗

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>,这是通过启动服务器返回的,而第二个示例以Ok(())的形式返回Result<(), anyhow::Error>.

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

the docs开始:

对于Err变量,它检索内部错误.try 然后使用From执行转换.这提供了特殊错误和更一般错误之间的自动转换.

Rust相关问答推荐

文档示例需要导入相关的 struct ,但仅在运行测试时.这是故意的行为吗?

下载压缩文件

为潜在的下游实现使用泛型绑定而不是没有泛型绑定的trait

有没有办法指定只在Rust的测试中有效的断言?

正则表达式中的重叠匹配?(铁 rust 正则式发动机)

如何在AVX2中对齐/旋转256位向量?

Rust将String上的迭代器转换为&;[&;str]

如何设置activx websocket actorless的消息大小限制?

为什么我需要 to_string 函数的参考?

Boxing 如何将数据从堆栈移动到堆?

通过写入 std::io::stdout() 输出不可见

实现AsyncWrite到hyper Sender时发生生命周期错误

max(ctz(x), ctz(y)) 有更快的算法吗?

从 HashMap>, _> 中删除的生命周期问题

如何在 Rust 中将 UTF-8 十六进制值转换为 char?

在 Rust 中,将可变引用传递给函数的机制是什么?

仅当满足外部条件时如何添加到 actix web 的路由

匹配结果时的简洁日志(log)记录

在 Rust 中获得准确时间的正确方法?

为什么 `ref` 会导致此示例*取消引用*一个字段?