面试题答案
一键面试在Rust中,模块内部函数默认是私有的,只有通过pub
关键字声明才能被外部模块访问。
对于结构体,默认情况下,结构体及其字段都是私有的。如果要使结构体可被外部模块访问,需要使用pub
关键字声明结构体本身。若想让结构体的字段也能被外部模块访问,还需分别对字段使用pub
关键字。
以下是一个简单项目结构示例,有两个模块:
// src/lib.rs
mod module1;
mod module2;
pub use module1::func1;
pub use module2::func2;
// src/module1.rs
pub fn func1() {
println!("This is func1 in module1");
}
// src/module2.rs
use crate::module1::func1;
pub fn func2() {
println!("Before calling func1 from module2");
func1();
println!("After calling func1 from module2");
}
在上述代码中:
- 在
module1.rs
里,func1
函数通过pub
关键字声明,这样其他模块就可以访问它。 - 在
module2.rs
里,通过use crate::module1::func1
引入module1
中的func1
函数,然后在func2
函数中调用。 - 在
lib.rs
中,通过pub use
将module1::func1
和module2::func2
重新导出,这样外部使用这个库的代码就可以直接访问func1
和func2
。