rust - 在单独的模块中使用时使用未声明的类型或模块 `std`

标签 rust rust-obsolete

我有以下代码:

pub mod a {
    #[test]
    pub fn test() {
        println!("{:?}", std::fs::remove_file("Somefilehere"));
    }
}

编译时出现错误:

error[E0433]: failed to resolve. Use of undeclared type or module `std`
 --> src/main.rs:4:24
  |
4 |         println!("{}", std::fs::remove_file("Somefilehere"));
  |                        ^^^ Use of undeclared type or module `std`

但是,删除内部模块并自行编译它包含的代码可以正常工作:

#[test]
pub fn test() {
    println!("{:?}", std::fs::remove_file("Somefilehere"));
}

我在这里错过了什么?如果模块在单独的文件中,我会得到同样的错误:

ma​​in.rs

pub mod a;

a.rs

#[test]
pub fn test() {
    println!("{:?}", std::fs::remove_file("Somefilehere"));
}

最佳答案

默认情况下,编译器会在 crate root 的开头插入 extern crate std;(crate root 是您传递给 rustc 的文件)。该语句的作用是将名称 std 添加到 crate 的根命名空间,并将其与包含 std crate 的公共(public)内容的模块相关联。

但是,在子模块中,std 不会自动添加到模块的命名空间中。这就是编译器无法解析模块中的 std(或以 std:: 开头的任何内容)的原因。

有很多方法可以解决这个问题。首先,您可以在模块中添加 use std;,使名称 std 在该模块中引用根 std。请注意,在 use 语句中,路径被视为绝对路径(或“相对于 crate 的根命名空间”),而在其他任何地方,路径都被视为相对于当前命名空间(无论是模块,函数等)。

pub mod a {
    use std;

    #[test]
    pub fn test() {
        println!("{:?}", std::fs::remove_file("Somefilehere"));
    }
}

您还可以使用 use 语句来导入更具体的项目。例如,您可以编写 use std::fs::remove_file;。这使您不必键入 remove_file 的整个路径,而只需在该模块中直接使用名称 remove_file:

pub mod a {
    use std::fs::remove_file;

    #[test]
    pub fn test() {
        println!("{:?}", remove_file("Somefilehere")));
    }
}

最后,您可以通过在路径前加上 :: 来避免使用 use 来要求编译器从 crate 的根命名空间解析路径(即转换路径成绝对路径)。

pub mod a {
    #[test]
    pub fn test() {
        println!("{:?}", ::std::fs::remove_file("Somefilehere"));
    }
}

推荐的做法是直接导入类型(结构、枚举等)(例如use std::rc::Rc;,然后使用路径Rc ),但要通过导入其父模块来使用函数(例如,使用 std::io::fs;,然后使用路径 fs::remove_file)。

pub mod a {
    use std::fs;

    #[test]
    pub fn test() {
        println!("{:?}", fs::remove_file("Somefilehere"));
    }
}

旁注:您还可以在路径的开头编写 self:: 以使其相对于当前模块。这在 use 语句中更常用,因为其他路径已经是相对的(尽管它们是相对于当前的 namespace,而 self::总是相对于包含的模块)。

关于rust - 在单独的模块中使用时使用未声明的类型或模块 `std`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23434378/

相关文章:

random - 在 Rust 中生成安全随机数

使用rust "error: moving out of immutable field"

vector - Rust 中的二维向量

ruby - 如何将模块中的方法带入 ruby​​ 中方法调用者的范围?

join - Diesel 连接无法推断类型

enums - "error: trait bounds are not allowed in structure definitions"尝试使用多态性时

使用rust 错误 "cannot determine a type for this expression"

rust - 如何在实现 Deref 的类型(例如 Box)内对值进行模式匹配,而不复制内容?

rust - 生成返回字符串的函数时,为什么 wasm-opt 在 wasm-pack 构建中失败?

multithreading - 是否可以在不锁定整个 HashMap 的情况下在线程之间共享一个 HashMap?