为什么Rust在子模块中找不到函数?

13

我正在尝试从位于另一个文件中的模块中调用一个公共函数,我使用完整路径进行调用,但rustc仍然抱怨"未解决的名称"。

a.rs

pub mod b;
fn main() {
  b::f()
}

b.rs

pub mod b {
    pub fn f(){
        println!("Hello World!");
    }
}

编译

$ rustc a.rs
a.rs:3:5: 3:9 error: unresolved name `b::f`.

当我将该模块移动到木箱的主文件时,一切都正常。

one_file.rs

pub mod b {
    pub fn f(){
        println!("Hello World!");
    }
}
fn main() {
    b::f()
}

这两种方式不应该是等效的吗?我是做错了什么,还是rustc有bug?

1个回答

23

当你有不同的文件时,它们会自动被视为不同的模块。

因此,你可以这样做:

othermod.rs

pub fn foo() {
}

pub mod submod {
    pub fn subfoo() {
    }
}

main.rs

mod othermod;

fn main ()  {
    othermod::foo();
    othermod::submod::subfoo();
}

请注意,如果您使用子目录,则文件mod.rs是特殊的,并且将被视为模块的根目录:

directory/file.rs

pub fn filebar() {
}

directory/mod.rs

pub mod file;

pub fn bar() {
}

main.rs

mod directory;

fn main() {
    directory::bar();
    directory::file::filebar();
}

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