在单独的模块中使用时使用未声明的类型或模块“std”

2024-02-29

我有以下代码:

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"));
}

我在这里缺少什么?如果模块位于单独的文件中,我会得到相同的错误:

main.rs

pub mod a;

a.rs

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

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

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

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

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完全通过在路径前加上前缀::要求编译器从包的根命名空间解析路径(即将路径转换为绝对路径)。

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

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

pub mod a {
    use std::fs;

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

边注:你也可以写self::在路径的开头,使其相对于当前模块。这个比较常用在use语句,因为其他路径已经是相对的(尽管它们是相对于当前的名称空间, 然而self::总是相对于包含的module).

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在单独的模块中使用时使用未声明的类型或模块“std” 的相关文章

随机推荐