`std::io::Error` 没有实现 `std::convert::From<mongodb::error::Error>` 特性。

4
尝试使用 Rust 的 actix-web 和 mongodb 创建服务器,但遇到以下错误:
“std::io::Error” 无法实现 “mongodb::error::Error”的 “std::convert::From” 特性。
以下是我的代码:
use actix_web::{web, App, HttpRequest, HttpServer, Responder};
use mongodb::{options::ClientOptions, Client};

async fn greet(req: HttpRequest) -> impl Responder {
    let name = req.match_info().get("name").unwrap_or("World");
    format!("Hello {}!", &name)
}

#[actix_rt::main]
async fn main() -> std::io::Result<()> {
    // Parse a connection string into an options struct.
    let mut client_options = ClientOptions::parse("mongodb://localhost:27017")?;

    // Manually set an option.
    client_options.app_name = Some("My App".to_string());

    // Get a handle to the deployment.
    let client = Client::with_options(client_options)?;

    // List the names of the databases in that deployment.
    for db_name in client.list_database_names(None)? {
        println!("{}", db_name);
    }

    HttpServer::new(|| {
        App::new()
            .route("/", web::get().to(greet))
            .route("/{name}", web::get().to(greet))
    })
    .bind("127.0.0.1:8000")?
    .run()
    .await
}

我错过了什么吗?

请[编辑]您的问题并粘贴您收到的确切和完整错误 - 这将帮助我们了解问题所在,以便我们能够提供最好的帮助。有时尝试解释错误消息是棘手的,实际上重要的是错误消息的不同部分。请使用直接运行编译器生成的消息,而不是IDE生成的消息,后者可能正在尝试为您解释错误。 - Shepmaster
1个回答

7

推理

它意味着你正在调用的函数之一以?结尾,可能返回一个mongodb::error::Error。但是main的签名是std::io::Result<()>,这是一个隐含的Result<(), std::io::Error>。它只能接受io::Error类型的错误,而不是mongodb::Error。

看起来你逃逸的所有函数可能都会返回这个mongodb::error::Error,所以你可以尝试将main的签名更改为这样一个结果:Result<(). mongodb::error::Error>。 但我建议你对这些潜在错误进行适当的错误处理,因为这是你的主函数。

解决方案

至少将那些?更改为.expect("Some error message");。程序仍然会崩溃,但它会以对你有意义的方式崩溃。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接