rust - 使用未声明的类型或模块 `HttpResponse` : not found in this scope

标签 rust rust-cargo

我必须承认,我很难理解 Rust 编译器的错误消息。
我有这个模块:
src/adapters.js

use actix_web::{Responder, HttpResponse};

pub mod Basic {

    pub fn api_index() -> &'static str {
        "API"
    }

    pub fn admin_index() -> impl Responder {
        HttpResponse::Ok().body("hello world!")
    }

}
当我使用 Rust 编译器时不断告诉我
use crate::actix_web::{Responder, HttpResponse};
那:
E0432: unresolved import `crate::actix_web`  maybe a missing crate `actix_web`?
请放心,crate::actix_web 并没有丢失,因为我可以运行来自 main.rs 的简单请求。当我想在自己的模块中使用 actix_web 模块时,问题就开始了。
如果我有
use actix_web::{Responder, HttpResponse};
Rust 一直在告诉我:
error[E0433]: failed to resolve: use of undeclared type or module `HttpResponse`

HttpResponse::Ok().body("hello world!")
^^^^^^^^^^^^ not found in this scope



help: consider importing one of these items
use actix_web::HttpResponse;
use crate::adapters::HttpResponse;


E0432: unresolved import `crate::actix_web`  maybe a missing crate `actix_web`?
我的 main.rs,作为第一行,我还声明:
extern crate actix_web;
为了确保起见,我还添加了“extern crate actix_web;”在开始时到 adapters.rs 模块。这也没有改变任何东西。
我的选择已经不多了,我不知道我还能做些什么。

最佳答案

基本上你已经在适配器模块中创建了另一个模块 Basic。所以 Basic 是 子模块 适配器模块。因此,在这种情况下,您可以通过两种方式访问​​外部 crate。

  • 在基本模块中导入外部 crate 模块。

  • pub mod Basic {
        use actix_web::{Responder, HttpResponse};
    
        pub fn api_index() -> &'static str {
            "API"
        }
    
        pub fn admin_index() -> impl Responder {
            HttpResponse::Ok().body("hello world!")
        }
    }
    
  • 或者在外部模块模块中导入一个外部模块,并在内部模块中使用 super 关键字访问这些模块。

  • use actix_web::{Responder, HttpResponse};
    
    pub mod Basic {
    
        pub fn api_index() -> &'static str {
            "API"
        }
    
        pub fn admin_index() -> impl super::Responder {
            super::HttpResponse::Ok().body("hello world!")
        }
    }
    

    关于rust - 使用未声明的类型或模块 `HttpResponse` : not found in this scope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64306649/

    相关文章:

    rust - 从切片构建固定大小数组的函数

    github - 如何在 Cargo.toml 中的依赖项中指定某个提交?

    documentation - 如何在文档测试中忽略一行到文档中?

    rust - 生命周期省略的第三条规则是否包含结构实现的所有情况?

    path - 给定两个绝对路径,我该如何表达相对于另一个的路径?

    error-handling - 替代适用于迭代器映射的 try (?) 运算符

    macos - Rust cargo dylib 说明

    time - 使用 Cargo 获取执行时间

    rust - 如何指定工作区成员只能在特定平台上构建?

    rust - 在 Windows 上编译 ruSTLess 的基本示例时出现 "could not rename crate"