默认情况下,编译器插入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).